docker容器增加端口映射最佳实践(修改配置文件方式)

前言:
在日常的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

8080
到这里,我们的环境已经搭建完成,接下来我们就要为容器增加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

3506
通过mysql客户端连接测试正常,说明端口映射成功!
docker容器增加端口映射最佳实践(修改配置文件方式)_第1张图片

2020.01.10 周五下班前 深圳南山

你可能感兴趣的:(linux,运维)