一、添加docker容器端口映射

以tomcat容器为例:

root@localhost /]# docker run --name mytomcat -d -p 8888:8080 tomcat

–name:创建的tomcat镜像名称
‐d:后台运行
‐p:将主机的端口映射到容器的一个端口,8888:8080代表:主机端口:容器内部的端口

执行完会返回新创建的tomcat镜像ID

二、修改docker容器端口映射

方法一
  • 1、查看tomcat镜像ID(docker ps)
root@localhost /]# docker ps
CONTAINER ID        IMAGE               COMMAND             CREATED             STATUS              PORTS                    NAMES
bf96392335e8        tomcat              "catalina.sh run"   5 minutes ago       Up 5 minutes        0.0.0.0:8888->8080/tcp   mytomcat
  • 2、停止容器(docker stop 镜像ID)
[root@localhost /]# docker stop bf96392335e8
  • 3、停止docker服务(systemctl stop docker)
[root@localhost /]# systemctl stop docker
  • 4、修改此容器的hostconfig.json文件中的映射端口,若config.v2.json里面也记录了端口,也要修改。
[root@localhost /]# cd /var/lib/docker/containers/bf96392335e8*
[root@localhost bf96392335e88f3a0825aaec15bdd23100e642e899b6c34f9d2c33299178c464]# vi hostconfig.json

hostcongfig.json:

{"Binds":null,"ContainerIDFile":"","LogConfig":{"Type":"journald","Config":{}},"NetworkMode":"default","PortBindings":{"8080/tcp":[{"HostIp":"","HostPort":"8888"}]},"RestartPolicy":{"Name":"no","Ma
ximumRetryCount":0},"AutoRemove":false,"VolumeDriver":"","VolumesFrom":null,"CapAdd":null,"CapDrop":null,"Dns":[],"DnsOptions":[],"DnsSearch":[],"ExtraHosts":null,"GroupAdd":null,"IpcMode":"","Cgro
up":"","Links":[],"OomScoreAdj":0,"PidMode":"","Privileged":false,"PublishAllPorts":false,"ReadonlyRootfs":false,"SecurityOpt":null,"UTSMode":"","UsernsMode":"","ShmSize":67108864,"Runtime":"docker
-runc","ConsoleSize":[0,0],"Isolation":"","CpuShares":0,"Memory":0,"NanoCpus":0,"CgroupParent":"","BlkioWeight":0,"BlkioWeightDevice":null,"BlkioDeviceReadBps":null,"BlkioDeviceWriteBps":null,"Blki
oDeviceReadIOps":null,"BlkioDeviceWriteIOps":null,"CpuPeriod":0,"CpuQuota":0,"CpuRealtimePeriod":0,"CpuRealtimeRuntime":0,"CpusetCpus":"","CpusetMems":"","Devices":[],"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”:{“8080/tcp”:[{“HostIp”:"",“HostPort”:“8888”}]}代表端口映射配置,修改HostPort项的值后保存退出。

  • 5、启动docker(systemctl start docker)
[root@localhost /]# systemctl start docker
  • 6、启动tomcat镜像(docker start 镜像ID)
[root@localhost /]# docker start bf96392335e8
方法二
  • 1、获得容器IP
    将container_name 换成实际环境中的容器名
docker inspect `container_name` | grep IPAddress
  • 2、iptable转发端口
    将宿主机的8888端口映射到IP为192.168.1.15容器的8080端口
iptables -t nat -A  DOCKER -p tcp --dport 8888 -j DNAT --to-destination 192.168.1.15:8080

Logo

权威|前沿|技术|干货|国内首个API全生命周期开发者社区

更多推荐