修改已运行docker容器端口映射

前言

在项目中我们一般通过命令启动一个容器的时候,通常会通过命令指定容器与物理机网络端口的映射。例如下面这个命令就会运行一个nginx容器,并且指定它的容器内的端口80与物理机中的端口8080进行映射。

 sudo docker run --name nginx-demo \
 -p 8080:80 \
 -d  nginx

因为端口映射一般是在容器建立的时候就设置好的了,有时我们需要对端口映射进行修改的时候就显得束手无策了,貌似目前docker还没有提供可以修改容器的端口映射命令。在网上检索的一些修改的方式,发现是通过修改docker配置文件进行修改,具体的操作步骤如下。

一、找到需要修改的配置文件

第一步要找到我们需要修改容器端口映射配置文件,具体的路径一般是/var/lib/docker/containers/{{CONTAINER ID}},容器的CONTAINER ID可以通过命令docker ps -a找到,执行命令如下

[root@localhost]# docker ps -a
CONTAINER ID        IMAGE               COMMAND                  CREATED             STATUS              PORTS                                      NAMES
16aeecf6ed6f        nginx               "nginx -g 'daemon ..."   9 minutes ago       Up 9 minutes        0.0.0.0:8080->80/tcp                       nginx-demo

其中16aeecf6ed6f就是我们要找的CONTAINER ID的部分前缀,该容器的配置目录名称就是已该名称前缀匹配的字符,我服务器上的完整CONTAINER ID是16aeecf6ed6fcc17793060ffac32315bbaa76a08eaee00062e31c74a01802470

通过以下命令进入到容器配置目录,可以看到如下文件

[root@localhost /]# cd /var/lib/docker/containers/16aeecf6ed6fcc17793060ffac32315bbaa76a08eaee00062e31c74a01802470
[root@localhost 16aeecf6ed6fcc17793060ffac32315bbaa76a08eaee00062e31c74a01802470]# ls
16aeecf6ed6fcc17793060ffac32315bbaa76a08eaee00062e31c74a01802470-json.log  checkpoints  config.v2.json  hostconfig.json  hostname  hosts  resolv.conf  resolv.conf.hash  shm

其中文件hostconfig.jsonconfig.v2.json就是我们要修改的配置文件

二、停止docker服务器,修改端口映射配置文件

在修改配置文件之前,我们要将正在运行的docker服务停止,通过systemctl stop docker或者 service docker stop

通过vi命令打开hostconfig.json文件,看到内容如下(PS:原配置文件JSON格式有点混乱我用工具格式化了一下)

{
	"Binds": null,
	"ContainerIDFile": "",
	"LogConfig": {
		"Type": "json-file",
		"Config": {}
	},
	"NetworkMode": "default",
	"PortBindings": {
		"80/tcp": [{
			"HostIp": "",
			"HostPort": "8080"
		}]
	},
	"RestartPolicy": {
		"Name": "no",
		"MaximumRetryCount": 0
	},
	"AutoRemove": false,
	"VolumeDriver": "",
	"VolumesFrom": null,
	"CapAdd": null,
	"CapDrop": null,
	"Dns": [],
	"DnsOptions": [],
	"DnsSearch": [],
	"ExtraHosts": null,
	"GroupAdd": null,
	"IpcMode": "",
	"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": null,
	"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": -1,
	"OomKillDisable": false,
	"PidsLimit": 0,
	"Ulimits": null,
	"CpuCount": 0,
	"CpuPercent": 0,
	"IOMaximumIOps": 0,
	"IOMaximumBandwidth": 0
}

从配置文件中可以看到字段名为PortBindings项下面有我们刚开始的创建容器时设定的端口映射项

"PortBindings": {
		"80/tcp": [{
			"HostIp": "",
			"HostPort": "8080"
		}]
	}

我们将该项修改为我们需要映射的新端口,比如8081

"PortBindings": {
		"80/tcp": [{
			"HostIp": "",
			"HostPort": "8081"
		}]
	}

然后继续修改第二个配置文件,通过vi命令打开hostconfig.json文件,看到内容如下(PS:原配置文件JSON格式有点混乱我用工具格式化了一下)

{
	"StreamConfig": {},
	"State": {
		"Running": false,
		"Paused": false,
		"Restarting": false,
		"OOMKilled": false,
		"RemovalInProgress": false,
		"Dead": false,
		"Pid": 0,
		"ExitCode": 0,
		"Error": "",
		"StartedAt": "2019-02-28T02:01:20.219978817Z",
		"FinishedAt": "2019-02-28T02:23:34.188640596Z",
		"Health": null
	},
	"ID": "16aeecf6ed6fcc17793060ffac32315bbaa76a08eaee00062e31c74a01802470",
	"Created": "2019-02-28T02:01:19.716013746Z",
	"Managed": false,
	"Path": "nginx",
	"Args": ["-g", "daemon off;"],
	"Config": {
		"Hostname": "16aeecf6ed6f",
		"Domainname": "",
		"User": "",
		"AttachStdin": false,
		"AttachStdout": false,
		"AttachStderr": false,
		"ExposedPorts": {
			"80/tcp": {}
		},
		"Tty": false,
		"OpenStdin": false,
		"StdinOnce": false,
		"Env": ["PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin", "NGINX_VERSION=1.13.5-1~stretch", "NJS_VERSION=1.13.5.0.1.13-1~stretch"],
		"Cmd": ["nginx", "-g", "daemon off;"],
		"ArgsEscaped": true,
		"Image": "nginx",
		"Volumes": null,
		"WorkingDir": "",
		"Entrypoint": null,
		"OnBuild": null,
		"Labels": {
			"maintainer": "NGINX Docker Maintainers \[email protected]\u003e"
		},
		"StopSignal": "SIGTERM"
	},
	"Image": "sha256:1e5ab59102ce46c277eda5ed77affaa4e3b06a59fe209fe0b05200606db3aa7a",
	"NetworkSettings": {
		"Bridge": "",
		"SandboxID": "d681fbde606c98843af298b2645627f7f52f8445327b1e40306357fb2d999fd0",
		"HairpinMode": false,
		"LinkLocalIPv6Address": "",
		"LinkLocalIPv6PrefixLen": 0,
		"Networks": {
			"bridge": {
				"IPAMConfig": null,
				"Links": null,
				"Aliases": null,
				"NetworkID": "fb9c9f61e3c225a2a6ec8bb10e691b8f0fc0fb416fd3916a998cdff221534a55",
				"EndpointID": "",
				"Gateway": "",
				"IPAddress": "",
				"IPPrefixLen": 0,
				"IPv6Gateway": "",
				"GlobalIPv6Address": "",
				"GlobalIPv6PrefixLen": 0,
				"MacAddress": "",
				"DriverOpts": null,
				"IPAMOperational": false
			}
		},
		"Service": null,
		"Ports": null,
		"SandboxKey": "/var/run/docker/netns/d681fbde606c",
		"SecondaryIPAddresses": null,
		"SecondaryIPv6Addresses": null,
		"IsAnonymousEndpoint": false,
		"HasSwarmEndpoint": false
	},
	"LogPath": "/var/lib/docker/containers/16aeecf6ed6fcc17793060ffac32315bbaa76a08eaee00062e31c74a01802470/16aeecf6ed6fcc17793060ffac32315bbaa76a08eaee00062e31c74a01802470-json.log",
	"Name": "/nginx-demo",
	"Driver": "overlay2",
	"MountLabel": "",
	"ProcessLabel": "",
	"RestartCount": 0,
	"HasBeenStartedBefore": true,
	"HasBeenManuallyStopped": false,
	"MountPoints": {},
	"SecretReferences": null,
	"ConfigReferences": null,
	"AppArmorProfile": "",
	"HostnamePath": "/var/lib/docker/containers/16aeecf6ed6fcc17793060ffac32315bbaa76a08eaee00062e31c74a01802470/hostname",
	"HostsPath": "/var/lib/docker/containers/16aeecf6ed6fcc17793060ffac32315bbaa76a08eaee00062e31c74a01802470/hosts",
	"ShmPath": "/var/lib/docker/containers/16aeecf6ed6fcc17793060ffac32315bbaa76a08eaee00062e31c74a01802470/shm",
	"ResolvConfPath": "/var/lib/docker/containers/16aeecf6ed6fcc17793060ffac32315bbaa76a08eaee00062e31c74a01802470/resolv.conf",
	"SeccompProfile": "",
	"NoNewPrivileges": false
}

其中的config.ExposedPorts就是我们要修改的端口映射配置项

 "Config": {
       ...
        "ExposedPorts": {
            "80/tcp": {}
        }
       ...
    }

和上面一样,我们将该项修改如下

 "Config": {
       ...
        "ExposedPorts": {
            "80/tcp": {"HostIp": "",
			"HostPort": "8081"}
        }
       ...
    }

三、重启docker服务,配置生效

最后执行docker容器重启命令systemctl start docker,启动容器之后就可以看到新增的端口映射了。

[root@localhost /]# docker ps
CONTAINER ID        IMAGE               COMMAND                  CREATED             STATUS              PORTS                                      NAMES
16aeecf6ed6f        nginx               "nginx -g 'daemon ..."   44 minutes ago      Up 2 minutes        0.0.0.0:8081->80/tcp                       nginx-demo

如有疑问,可以在下面留言!
更多精彩分享,请点击这里~~

你可能感兴趣的:(Linux相关,docker相关)