如何修改运行中的docker容器的端口映射和挂载目录

时间:2022-02-24 16:12:12

在docker run创建并运行容器的时候,可以通过-p指定端口映射规则。但是,我们经常会遇到刚开始忘记设置端口映射或者设置错了需要修改。当docker start运行容器后并没有提供一个-p选项或设置,让你修改指定端口映射规则。那么这种情况我们该怎么处理呢?今天Docker君教你如何修改运行中的docker容器的端口映射?

方法一:删除原有容器,重新建新容器

这个解决方案最为简单,把原来的容器删掉,重新建一个。当然这次不要忘记加上端口映射。

优缺点:优点是简单快捷,在测试环境使用较多。缺点是如果是数据库镜像,那重新建一个又要重新配置一次,就比较麻烦了。

方法二:修改容器配置文件,重启docker服务

容器的配置文件路径:

  1. /var/lib/docker/containers/[hash_of_the_container]/hostconfig.json

其中的hashofthecontainer是docker镜像的hash值,可以通过docker ps或者docker inspect containername查看。(CONTAINER ID就可以看出来)

[root@ecs- ~]# docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
f8511e56585f gitlab/gitlab-ce:latest "/assets/wrapper" months ago Up hours (healthy) 0.0.0.0:->/tcp, 0.0.0.0:->/tcp, 0.0.0.0:->/tcp gitlab-ce
[root@ecs- ~]#
[root@ecs- ~]#
[root@ecs- ~]# cat /var/lib/docker/containers/f8511e56585fdd68d4bb5ad57250d829bac52626d722305a43dec1e5cf18406c/hostconfig.json
{"Binds":["/srv/gitlab/logs:/var/log/gitlab","/srv/gitlab/data:/var/opt/gitlab","/srv/gitlab/config:/etc/gitlab"],"ContainerIDFile":"","LogConfig":{"Type":"journald","Config":{}},"NetworkMode":"default","PortBindings":{"22/tcp":[{"HostIp":"","HostPort":""}],"443/tcp":[{"HostIp":"","HostPort":""}],"80/tcp":[{"HostIp":"","HostPort":""}]},"RestartPolicy":{"Name":"always","MaximumRetryCount":},"AutoRemove":false,"VolumeDriver":"","VolumesFrom":null,"CapAdd":null,"CapDrop":null,"Dns":[],"DnsOptions":[],"DnsSearch":[],"ExtraHosts":null,"GroupAdd":null,"IpcMode":"","Cgroup":"","Links":[],"OomScoreAdj":,"PidMode":"","Privileged":false,"PublishAllPorts":false,"ReadonlyRootfs":false,"SecurityOpt":null,"UTSMode":"","UsernsMode":"","ShmSize":,"Runtime":"docker-runc","ConsoleSize":[,],"Isolation":"","CpuShares":,"Memory":,"NanoCpus":,"CgroupParent":"","BlkioWeight":,"BlkioWeightDevice":null,"BlkioDeviceReadBps":null,"BlkioDeviceWriteBps":null,"BlkioDeviceReadIOps":null,"BlkioDeviceWriteIOps":null,"CpuPeriod":,"CpuQuota":,"CpuRealtimePeriod":,"CpuRealtimeRuntime":,"CpusetCpus":"","CpusetMems":"","Devices":[],"DiskQuota":,"KernelMemory":,"MemoryReservation":,"MemorySwap":,"MemorySwappiness":-,"OomKillDisable":false,"PidsLimit":,"Ulimits":null,"CpuCount":,"CpuPercent":,"IOMaximumIOps":,"IOMaximumBandwidth":}
[root@ecs- ~]#

按需修改端口, 按需修改挂载目录(权限和属主属组要相同),然后重启docker服务,再启动容器服务就可以了。

systemctl restart docker

优缺点:这个方法的优点是没有副作用,操作简单。缺点是需要重启整个docker服务,如果在同一个宿主机上运行着多个容器服务的话,就会影响其他容器服务。