已有的docker容器增加新的端口映射

在指定容器运行时要运行的映射端口后,如果您想要添加新的端口映射,可以使用这两种方法中的任何一种。有需要的朋友可以参考一下。

[En]

After specifying the mapping port to run when the container is running, if you want to add a new port mapping, you can use either of these two ways. Friends who need it can refer to it.

一般在运行容器时,我们都会通过参数 -p(使用大写的-P参数则会随机选择宿主机的一个端口进行映射)来指定宿主机和容器端口的映射,例如

docker run -it -d --name [container-name] -p 8088:80 [image-name]

这里是将容器内的80端口到宿主机的8088端口

在指定容器运行时要运行的映射端口后,如果要添加新的端口映射,可以使用以下两种方式:

[En]

After specifying the mapped port to run when the container is running, if you want to add a new port mapping, you can use the following two ways:

将已有的容器打包成镜像,然后在使用新镜像运行容器时重新分配要映射的端口

[En]

Package the existing container into an image, and then reassign the port to be mapped when running the container with the new image

#1、停止现有容器
docker stop container-name
#2、将容器commit成为一个镜像
docker commit -a "作者" -m "a new image" [容器名称或id] [打包的镜像名称]:[版本标签]
#常用OPTIONS说明:
   -a :提交的镜像作者
   -c :使用Dockerfile指令来创建镜像
   -m :提交时的说明文字
   -p :在commit时,将容器暂停

#或者使用export和import将容器导出为镜像
docker export 容器ID > 压缩包名称.tar
cat 压缩包名称.tar | docker import - 镜像名称:版本标签
#例如:
#导出
$ docker export 1efca3906 > centos.tar
#导入
$ cat docker/centos.tar | docker import - test/centos:v1

#3、用新的镜像生成一个新的容器并配置需要的映射端口
docker run -it -d --name container-name -p p1:p1 -p p2:p2 new-image-name

修改容器配置文件进行端口映射(推荐)

[En]

Modify the configuration file of the container for port mapping (recommended)

#1、查看容器的信息
docker ps -a

#2、查看容器的端口映射情况,在容器外执行:
docker port 容器ID 或者 docker port 容器名称

#3、查找要修改容器的全ID
docker inspect 容器ID |grep Id

#4、进到/var/lib/docker/containers 目录下找到与全 Id 相同的目录,修改 其中的hostconfig.json 和 config.v2.json文件:
#注意:若该容器还在运行中,需要先停掉
docker stop 容器ID
#再停掉docker服务
systemctl stop docker

#5、修改hostconfig.json如下
#   格式如:"{容器内部端口}/tcp":[{"HostIp":"","HostPort":"映射的宿主机端口"}]
"PortBindings":{"22/tcp":[{"HostIp":"","HostPort":"3316"}],"80/tcp":[{"HostIp":"","HostPort":"180"}]}

#6、修改config.v2.json在ExposedPorts中加上要暴露的端口
#   格式如:"{容器内部端口}/tcp":{}
"ExposedPorts":{"22/tcp":{},"80/tcp":{}}

最后改完之后,重启docker服务

systemctl restart docker

此时,您可以检查主机端口是否成功映射到容器内的端口,并在容器外执行。

[En]

At this point, you can check whether the host port is mapped successfully to the port in the container, and execute outside the container.

netstat -an | 宿主机的映射端口

Original: https://www.cnblogs.com/sthpr/p/16301088.html
Author: 三途河畔人
Title: 已有的docker容器增加新的端口映射

原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/523527/

转载文章受原作者版权保护。转载请注明原作者出处!

(0)

大家都在看

亲爱的 Coder【最近整理,可免费获取】👉 最新必读书单  | 👏 面试题下载  | 🌎 免费的AI知识星球