3

骚操作!居然能修改已运行的 Docker 容器端口映射?

 1 year ago
source link: https://www.51cto.com/article/716102.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
71dd67f779c24bfb221094fde213816327d8b7.jpg

容器未启动?

如果你的容器还没有构建时,想添加端口映射时,你只需要在创建容器的时候添加 -p 参数,想添加几个端口映射就追加几个 -p 参数。类似于如下示例:

docker run --name api_dfo_hyperf_ws \
-v /Users/pudongping/glory/codes/dfo/api_dfo_hyperf:/api_dfo_hyperf \
-p 9502:9502 \
-p 9503:9503 \
-p 9504:9504 \
-p 9505:9505 -it \
--entrypoint /bin/sh \
alex/alex_api_dfo:v1.0

容器已启动?

但是想修改或者添加端口时,先停止掉正在运行的容器。

以下内容都是以容器 id 为 cbe26510c276 进行操作的,请务必将容器 id 换成你自己需要修改的容器 id。

docker stop {容器的名称或者 id }
docker stop cbe26510c276

查看容器完整的 hash_of_the_container 数值:

docker inspect {容器的名称或者 id } | grep Id

# 比如:
docker inspect cbe26510c276 | grep Id
# 会得到如下结果:
# "Id": "cbe26510c276fa9a4487a8c2af8cbb49410f2a5305149d2b26eb8ce37c777d00"

打开 hostconfig.json 配置文件:

vim /var/lib/docker/containers/{hash_of_the_container}/hostconfig.json
vim /var/lib/docker/containers/cbe26510c276fa9a4487a8c2af8cbb49410f2a5305149d2b26eb8ce37c777d00/hostconfig.json

如果你不想先查看完整的容器 hash_of_the_container 数值,你也可以直接先切换到当前容器相关目录中 cd /var/lib/docker/containers/{hash_of_the_container}* , 然后再去编辑 hostconfig.json 配置文件。

cd /var/lib/docker/containers/{hash_of_the_container}*
cd /var/lib/docker/containers/cbe26510c276*

然后再去编辑 hostconfig.json 配置文件:

vim hostconfig.json

修改 hostconfig.json 配置文件

在 hostconfig.json 配置文件中,找到 "PortBindings":{} 这个配置项,然后进行修改。我这里添加了两个端口映射,分别将宿主机的 8502 端口以及 8505 端口映射到容器的 8502 端口和 8505 端口。

HostPort 对应的端口代表 宿主机 的端口。

建议容器使用什么端口,宿主机就映射什么端口,方便以后管理。当然,具体情况,具体分析。

{
    "PortBindings": {
        "8502/tcp": [
            {
                "HostIp": "",
                "HostPort": "8502"
            }
        ],
        "8505/tcp": [
            {
                "HostIp": "",
                "HostPort": "8505"
            }
        ]
    }
}

如果 config.v2.json 配置文件或者 config.json 配置文件中也记录了端口,也需要进行修改,如果没有,就不需要改。

只需要修改 "ExposedPorts": {} 相关之处。

{
    "Args": [],
    "Config": {
        "ExposedPorts": {
            "8502/tcp": {},
            "8505/tcp": {}
        },
        "Entrypoint": [
            "/bin/sh"
        ]
    }
}

最后重启 docker,然后查看容器相关配置信息是否已经修改完毕:

# 重启 docker
service docker restart
# 或者
systemctl restart docker

查看容器相关配置信息:

docker inspect {容器的名称或者 id }
# 比如:
docker inspect cbe26510c276

配置符合你的要求后,再次启动容器:

docker start {容器的名称或者 id }
# 比如:
docker start cbe26510c276

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK