当前位置: 代码网 > 服务器>服务器>云虚拟主机 > docker容器增加端口映射全过程(修改配置文件方式)

docker容器增加端口映射全过程(修改配置文件方式)

2024年11月25日 云虚拟主机 我要评论
前言:在日常的docker运维中,经常遇到这样一个问题:已经配置好且运行的docker容器要根据业务需要增加端口映射到宿主机,如何简单有效的解决呢?下面以mysql容器为例,详细说明操作步骤。一、环境

前言:

在日常的docker运维中,经常遇到这样一个问题:已经配置好且运行的docker容器要根据业务需要增加端口映射到宿主机,如何简单有效的解决呢?

下面以mysql容器为例,详细说明操作步骤。

一、环境准备

 # cat /etc/redhat-release 
 centos linux release 7.7.1908 (core)
 # docker --version
 docker version 17.09.1-ce, build 19e2cf6

docker-ce 安装说明

1、彻底卸载docker命令(如有安装)

# yum -y remove docker docker-common docker-selinux docker-engine

2、添加yum源

# yum-config-manager   --add-repo  https://download.docker.com/linux/centos/docker-ce.repo
 
loaded plugins: fastestmirror, langpacks
adding repo from: https://download.docker.com/linux/centos/docker-ce.repo
grabbing file https://download.docker.com/linux/centos/docker-ce.repo to /etc/yum.repos.d/docker-ce.repo
repo saved to /etc/yum.repos.d/docker-ce.repo

3、查看版本列表

# yum list docker-ce --showduplicates | sort -r

 * updates: mirrors.aliyun.com
loading mirror speeds from cached hostfile
loaded plugins: fastestmirror, langpacks
 * extras: mirrors.163.com
docker-ce.x86_64            3:19.03.5-3.el7                     docker-ce-stable
docker-ce.x86_64            3:19.03.4-3.el7                     docker-ce-stable
docker-ce.x86_64            3:19.03.3-3.el7                     docker-ce-stable
docker-ce.x86_64            3:19.03.2-3.el7                     docker-ce-stable
docker-ce.x86_64            3:19.03.1-3.el7                     docker-ce-stable
docker-ce.x86_64            3:19.03.0-3.el7                     docker-ce-stable
docker-ce.x86_64            3:18.09.9-3.el7                     docker-ce-stable
docker-ce.x86_64            3:18.09.8-3.el7                     docker-ce-stable
docker-ce.x86_64            3:18.09.7-3.el7                     docker-ce-stable
docker-ce.x86_64            3:18.09.6-3.el7                     docker-ce-stable
docker-ce.x86_64            3:18.09.5-3.el7                     docker-ce-stable
docker-ce.x86_64            3:18.09.4-3.el7                     docker-ce-stable
docker-ce.x86_64            3:18.09.3-3.el7                     docker-ce-stable
docker-ce.x86_64            3:18.09.2-3.el7                     docker-ce-stable
docker-ce.x86_64            3:18.09.1-3.el7                     docker-ce-stable
docker-ce.x86_64            3:18.09.0-3.el7                     docker-ce-stable
docker-ce.x86_64            18.06.3.ce-3.el7                    docker-ce-stable
docker-ce.x86_64            18.06.2.ce-3.el7                    docker-ce-stable
docker-ce.x86_64            18.06.1.ce-3.el7                    docker-ce-stable
docker-ce.x86_64            18.06.0.ce-3.el7                    docker-ce-stable
docker-ce.x86_64            18.03.1.ce-1.el7.centos             docker-ce-stable
docker-ce.x86_64            18.03.0.ce-1.el7.centos             docker-ce-stable
docker-ce.x86_64            17.12.1.ce-1.el7.centos             docker-ce-stable
docker-ce.x86_64            17.12.0.ce-1.el7.centos             docker-ce-stable
docker-ce.x86_64            17.09.1.ce-1.el7.centos             docker-ce-stable
docker-ce.x86_64            17.09.0.ce-1.el7.centos             docker-ce-stable
docker-ce.x86_64            17.06.2.ce-1.el7.centos             docker-ce-stable
docker-ce.x86_64            17.06.1.ce-1.el7.centos             docker-ce-stable
docker-ce.x86_64            17.06.0.ce-1.el7.centos             docker-ce-stable
docker-ce.x86_64            17.03.3.ce-1.el7                    docker-ce-stable
docker-ce.x86_64            17.03.2.ce-1.el7.centos             docker-ce-stable
docker-ce.x86_64            17.03.1.ce-1.el7.centos             docker-ce-stable
docker-ce.x86_64            17.03.0.ce-1.el7.centos             docker-ce-stable
 * base: mirrors.aliyun.com
available packages
[root@centos7-2 ~]# 

4、安装指定版本

# yum -y install yum install docker-ce-17.09.1.ce

loaded plugins: fastestmirror, langpacks
loading mirror speeds from cached hostfile
 * base: mirrors.zju.edu.cn
 * extras: mirrors.ustc.edu.cn
 * updates: mirrors.cqu.edu.cn
resolving dependencies
--> running transaction check
---> package docker-ce.x86_64 0:17.09.1.ce-1.el7.centos will be installed
--> processing dependency: container-selinux >= 2.9 for package: docker-ce-17.09.1.ce-1.el7.centos.x86_64
--> running transaction check
---> package container-selinux.noarch 2:2.107-3.el7 will be installed
--> finished dependency resolution

dependencies resolved

================================================================================================================================================================================================================================================================
 package                                                        arch                                                version                                                                 repository                                                     size
================================================================================================================================================================================================================================================================
installing:
 docker-ce                                                      x86_64                                              17.09.1.ce-1.el7.centos                                                 docker-ce-stable                                               21 m
installing for dependencies:
 container-selinux                                              noarch                                              2:2.107-3.el7                                                           extras                                                         39 k

transaction summary
================================================================================================================================================================================================================================================================
install  1 package (+1 dependent package)

total download size: 21 m
installed size: 21 m
is this ok [y/d/n]: y
downloading packages:
(1/2): container-selinux-2.107-3.el7.noarch.rpm                                                                                                                                                                                          |  39 kb  00:00:00     
docker-ce-17.09.1.ce-1.el7.cen failed                                                                             4% [====                                                                                                    ]  6.1 b/s | 888 kb 967:27:44 eta 
https://download.docker.com/linux/centos/7/x86_64/stable/packages/docker-ce-17.09.1.ce-1.el7.centos.x86_64.rpm: [errno 12] timeout on https://download.docker.com/linux/centos/7/x86_64/stable/packages/docker-ce-17.09.1.ce-1.el7.centos.x86_64.rpm: (28, 'operation too slow. less than 1000 bytes/sec transferred the last 30 seconds')
trying other mirror.
docker-ce-17.09.1.ce-1.el7.cen failed                                                                             28% [=============================                                                                          ]  290 b/s | 6.0 mb  15:14:31 eta 
https://download.docker.com/linux/centos/7/x86_64/stable/packages/docker-ce-17.09.1.ce-1.el7.centos.x86_64.rpm: [errno 12] timeout on https://download.docker.com/linux/centos/7/x86_64/stable/packages/docker-ce-17.09.1.ce-1.el7.centos.x86_64.rpm: (28, 'operation too slow. less than 1000 bytes/sec transferred the last 30 seconds')
trying other mirror.
docker-ce-17.09.1.ce-1.el7.cen failed                                                                             43% [============================================-                                                          ]  179 b/s | 9.2 mb  19:30:22 eta 
https://download.docker.com/linux/centos/7/x86_64/stable/packages/docker-ce-17.09.1.ce-1.el7.centos.x86_64.rpm: [errno 12] timeout on https://download.docker.com/linux/centos/7/x86_64/stable/packages/docker-ce-17.09.1.ce-1.el7.centos.x86_64.rpm: (28, 'operation too slow. less than 1000 bytes/sec transferred the last 30 seconds')
trying other mirror.
docker-ce-17.09.1.ce-1.el7.cen failed                                                                             59% [=============================================================                                          ]  264 b/s |  13 mb  09:29:11 eta 
https://download.docker.com/linux/centos/7/x86_64/stable/packages/docker-ce-17.09.1.ce-1.el7.centos.x86_64.rpm: [errno 12] timeout on https://download.docker.com/linux/centos/7/x86_64/stable/packages/docker-ce-17.09.1.ce-1.el7.centos.x86_64.rpm: (28, 'operation too slow. less than 1000 bytes/sec transferred the last 30 seconds')
trying other mirror.
(2/2): docker-ce-17.09.1.ce-1.el7.centos.x86_64.rpm                                                                                                                                                                                      |  21 mb  00:00:06     
----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
total                                                                                                                                                                                                                            99 kb/s |  21 mb  00:03:37     
running transaction check
running transaction test
transaction test succeeded
running transaction
  installing : 2:container-selinux-2.107-3.el7.noarch                                                                                                                                                                                                       1/2 
setsebool:  selinux is disabled.
  installing : docker-ce-17.09.1.ce-1.el7.centos.x86_64                                                                                                                                                                                                     2/2 
  verifying  : docker-ce-17.09.1.ce-1.el7.centos.x86_64                                                                                                                                                                                                     1/2 
  verifying  : 2:container-selinux-2.107-3.el7.noarch                                                                                                                                                                                                       2/2 

installed:
  docker-ce.x86_64 0:17.09.1.ce-1.el7.centos                                                                                                                                                                                                                    

dependency installed:
  container-selinux.noarch 2:2.107-3.el7                                                                                                                                                                                                                        

complete!

二、建立容器

1、查看mysql镜像列表

# docker search mysql

name                              description                                     stars               official            automated
mysql                             mysql is a widely used, open-source relati...   9013                [ok]                
mariadb                           mariadb is a community-developed fork of m...   3184                [ok]                
mysql/mysql-server                optimized mysql server docker images. crea...   671                                     [ok]
centos/mysql-57-centos7           mysql 5.7 sql database server                   67                                      
centurylink/mysql                 image containing mysql. optimized to be li...   61                                      [ok]
mysql/mysql-cluster               experimental mysql cluster docker images. ...   59                                      
deitch/mysql-backup               replaced! please use http://hub.docker.com...   41                                      [ok]
bitnami/mysql                     bitnami mysql docker image                      35                                      [ok]
tutum/mysql                       base docker image to run a mysql database ...   34                                      
schickling/mysql-backup-s3        backup mysql to s3 (supports periodic back...   28                                      [ok]
prom/mysqld-exporter                                                              24                                      [ok]
linuxserver/mysql                 a mysql container, brought to you by linux...   24                                      
centos/mysql-56-centos7           mysql 5.6 sql database server                   17                                      
circleci/mysql                    mysql is a widely used, open-source relati...   16                                      
mysql/mysql-router                mysql router provides transparent routing ...   14                                      
arey/mysql-client                 run a mysql client from a docker container      13                                      [ok]
openshift/mysql-55-centos7        deprecated: a centos7 based mysql v5.5 ima...   6                                       
yloeffler/mysql-backup            this image runs mysqldump to backup data u...   6                                       [ok]
genschsa/mysql-employees          mysql employee sample database                  4                                       [ok]
fradelg/mysql-cron-backup         mysql/mariadb database backup using cron t...   4                                       [ok]
devilbox/mysql                    retagged mysql, mariadb and perconadb offi...   2                                       
ansibleplaybookbundle/mysql-apb   an apb which deploys rhscl mysql                2                                       [ok]
jelastic/mysql                    an image of the mysql database server main...   1                                       
monasca/mysql-init                a minimal decoupled init container for mysql    0                                       
widdpim/mysql-client              dockerized mysql client (5.7) including cu...   0                                       [ok]

2、拉取指定镜像

# docker pull  mysql:5.6

5.6: pulling from library/mysql
804555ee0376: pull complete 
c53bab458734: pull complete 
ca9d72777f90: pull complete 
2d7aad6cb96e: pull complete 
8d6ca35c7908: pull complete 
dfc42a380610: pull complete 
fea6d62a8576: pull complete 
f59b0c57b762: pull complete 
aa66d796007b: pull complete 
6ac072c882e7: pull complete 
35f5014f1a5a: pull complete 
digest: sha256:82a505551c0243ca04df445f1287b2c4da3b23463b1a9c0bc2b2476760179950
status: downloaded newer image for mysql:5.6

# docker images
repository          tag                 image id            created             size
mysql               5.6                 f7ba8643e01a        11 days ago         302mb

3、通过镜像建立容器

这里我们只映射宿主机8080端口到docker容器的80端口

# docker run -it -d --restart always --name mysql-01 -e mysql_root_password=123456  -p 8080:80 f7ba8643e01a
ce265106bd99eb19cbc7f30db811cbcbc3de9bf0976e23fbaad65cb0e7e6ba92

查看容器状态

 # docker ps
container id        image               command                  created             status              ports                            names
ce265106bd99        f7ba8643e01a        "docker-entrypoint..."   3 seconds ago       up 2 seconds        3306/tcp, 0.0.0.0:8080->80/tcp   mysql-01

到这里,我们的环境已经搭建完成,接下来我们就要为容器增加3306 mysql服务器的端口映射

三、增加端口映射

现在我们来通过修改docker容器的配置文件实现端口映射,文件路径为 /var/lib/docker/containers/容器id

本人环境下的实际路径为:

/var/lib/docker/containers/ce265106bd99eb19cbc7f30db811cbcbc3de9bf0976e23fbaad65cb0e7e6ba92

# cd /var/lib/docker/containers/ce265106bd99eb19cbc7f30db811cbcbc3de9bf0976e23fbaad65cb0e7e6ba92
#  ll
total 64
-rw-r----- 1 root root 38507 jan  9 16:38 ce265106bd99eb19cbc7f30db811cbcbc3de9bf0976e23fbaad65cb0e7e6ba92-json.log
drwx------ 2 root root     6 jan  9 16:36 checkpoints
-rw------- 1 root root  2923 jan  9 16:38 config.v2.json
-rw-r--r-- 1 root root  1199 jan  9 16:38 hostconfig.json
-rw-r--r-- 1 root root    13 jan  9 16:36 hostname
-rw-r--r-- 1 root root   174 jan  9 16:36 hosts
-rw-r--r-- 1 root root    82 jan  9 16:36 resolv.conf
-rw-r--r-- 1 root root    71 jan  9 16:36 resolv.conf.hash
drwx------ 2 root root     6 jan  9 16:36 shm

这里可以看到有两个json文件:

hostconfig.json—— 配置宿主机和docker容器的端口映射关系

{"binds":null,"containeridfile":"","logconfig":{"type":"json-file","config":{}},"networkmode":"default","portbindings":{"80/tcp":[{"hostip":"","hostport":"8080"}],"3306/tcp":[{"hostip":"","hostport":"3506"}]},"restartpolicy":{"name":"always","maximumretrycount":0},"autoremove":false,"volumedriver":"","volumesfrom":null,"capadd":null,"capdrop":null,"dns":[],"dnsoptions":[],"dnssearch":[],"extrahosts":null,"groupadd":null,"ipcmode":"shareable","cgroup":"","links":null,"oomscoreadj":0,"pidmode":"","privileged":false,"publishallports":false,"readonlyrootfs":false,"securityopt":null,"utsmode":"","usernsmode":"","shmsize":67108864,"runtime":"runc","consolesize":[0,0],"isolation":"","cpushares":0,"memory":0,"nanocpus":0,"cgroupparent":"","blkioweight":0,"blkioweightdevice":[],"blkiodevicereadbps":null,"blkiodevicewritebps":null,"blkiodevicereadiops":null,"blkiodevicewriteiops":null,"cpuperiod":0,"cpuquota":0,"cpurealtimeperiod":0,"cpurealtimeruntime":0,"cpusetcpus":"","cpusetmems":"","devices":[],"devicecgrouprules":null,"diskquota":0,"kernelmemory":0,"memoryreservation":0,"memoryswap":0,"memoryswappiness":null,"oomkilldisable":false,"pidslimit":0,"ulimits":null,"cpucount":0,"cpupercent":0,"iomaximumiops":0,"iomaximumbandwidth":0}

config.v2.json —— docker容器的端口

{"streamconfig":{},"state":{"running":false,"paused":false,"restarting":false,"oomkilled":false,"removalinprogress":false,"dead":false,"pid":0,"exitcode":0,"error":"","startedat":"2020-01-09t08:36:14.519441922z","finishedat":"2020-01-09t08:38:39.994812777z","health":null},"id":"ce265106bd99eb19cbc7f30db811cbcbc3de9bf0976e23fbaad65cb0e7e6ba92","created":"2020-01-09t08:36:14.149947925z","managed":false,"path":"docker-entrypoint.sh","args":["mysqld"],"config":{"hostname":"ce265106bd99","domainname":"","user":"","attachstdin":false,"attachstdout":false,"attachstderr":false,"exposedports":{"3306/tcp":{},"80/tcp":{}},"tty":true,"openstdin":true,"stdinonce":false,"env":["mysql_root_password=123456","path=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin","gosu_version=1.7","mysql_major=5.6","mysql_version=5.6.46-1debian9"],"cmd":["mysqld"],"argsescaped":true,"image":"f7ba8643e01a","volumes":{"/var/lib/mysql":{}},"workingdir":"","entrypoint":["docker-entrypoint.sh"],"onbuild":null,"labels":{}},"image":"sha256:f7ba8643e01a1b582ffcf90cd5eab5ba97af396703ce9b6e2e292f6bbacd1d04","networksettings":{"bridge":"","sandboxid":"261f828c8935a0398c3f63cdef17c3bee413a3bb3ac924f3d57f36d4d644860e","hairpinmode":false,"linklocalipv6address":"","linklocalipv6prefixlen":0,"networks":{"bridge":{"ipamconfig":null,"links":null,"aliases":null,"networkid":"c10113ebd3a94dfae806c32f17ad37bdd6538ba24584dce63dda3c457b16cea5","endpointid":"","gateway":"","ipaddress":"","ipprefixlen":0,"ipv6gateway":"","globalipv6address":"","globalipv6prefixlen":0,"macaddress":"","driveropts":null,"ipamoperational":false}},"service":null,"ports":null,"sandboxkey":"/var/run/docker/netns/261f828c8935","secondaryipaddresses":null,"secondaryipv6addresses":null,"isanonymousendpoint":false,"hasswarmendpoint":false},"logpath":"/var/lib/docker/containers/ce265106bd99eb19cbc7f30db811cbcbc3de9bf0976e23fbaad65cb0e7e6ba92/ce265106bd99eb19cbc7f30db811cbcbc3de9bf0976e23fbaad65cb0e7e6ba92-json.log","name":"/mysql-01","driver":"overlay","platform":"linux","mountlabel":"","processlabel":"","restartcount":0,"hasbeenstartedbefore":true,"hasbeenmanuallystopped":false,"mountpoints":{"/var/lib/mysql":{"source":"","destination":"/var/lib/mysql","rw":true,"name":"7bac0015730f3eef9b3cb326b3c56c3eb0ae540938165a3c2d3c6e0b92dfe375","driver":"local","type":"volume","spec":{}}},"secretreferences":null,"configreferences":null,"apparmorprofile":"","hostnamepath":"/var/lib/docker/containers/ce265106bd99eb19cbc7f30db811cbcbc3de9bf0976e23fbaad65cb0e7e6ba92/hostname","hostspath":"/var/lib/docker/containers/ce265106bd99eb19cbc7f30db811cbcbc3de9bf0976e23fbaad65cb0e7e6ba92/hosts","shmpath":"/var/lib/docker/containers/ce265106bd99eb19cbc7f30db811cbcbc3de9bf0976e23fbaad65cb0e7e6ba92/shm","resolvconfpath":"/var/lib/docker/containers/ce265106bd99eb19cbc7f30db811cbcbc3de9bf0976e23fbaad65cb0e7e6ba92/resolv.conf","seccompprofile":"","nonewprivileges":false}

【注意】修改容器的配置文件之前,一定要停掉docker服务

#service docker stop

在 hostconfig.json 里有 “portbindings”:{} 这个配置项,可以改成 “portbindings”:{“80/tcp”:[{“hostip”:"",“hostport”:“8080”}],“3306/tcp”:[{“hostip”:"",“hostport”:“3506”}]}, 黄色部分为增加内容,这里 3306 是容器端口, 3506是宿主机端口;

在 config.v2.json 里面 “exposedports”:{“3306/tcp”:{},“80/tcp”:{}},“tty”:true 容器已经开启了3306端口,不用增加;

修改完成后,启动docker服务

# service docker start
redirecting to /bin/systemctl start docker.service

查看容器,可以看到3306端口已经映射到了主机的3506上

# docker ps
container id        image               command                  created             status              ports                                          names
ce265106bd99        f7ba8643e01a        "docker-entrypoint..."   6 minutes ago       up 4 seconds        0.0.0.0:8080->80/tcp, 0.0.0.0:3506->3306/tcp   mysql-01

通过mysql客户端连接测试正常,说明端口映射成功!

总结

以上为个人经验,希望能给大家一个参考,也希望大家多多支持代码网。

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2025  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com