当外部要访问容器中运行的应用时,可以通过-P或者-p来指定映射的端口。
-P:Docker会随机分配一个端口
-p:指定端口
例如:
# docker run -d -P nginx cd54a3d0c6895faed4b14cec1b174bce3f7e0b95acd22da9ac36f3e3d25d4f44 # docker ps -a CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES cd54a3d0c689 nginx "nginx -g 'daemon of…" 3 seconds ago Up 3 seconds 0.0.0.0:32768->80/tcp youthful_ramanujan 0bc2d24ca043 registry:2 "/entrypoint.sh /etc…" 22 hours ago Up 6 hours 0.0.0.0:5000->5000/tcp registry
可以看到本机的32768端口映射到容器的80端口,访问本机的32768端口
docker logs 查看应用信息
# docker logs -f cd54a3d0c689 172.16.0.10 - - [14/Jun/2018:08:06:29 +0000] "GET / HTTP/1.1" 200 612 "-" "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.181 Safari/537.36" "-" 2018/06/14 08:06:29 [error] 5#5: *1 open() "/usr/share/nginx/html/favicon.ico" failed (2: No such file or directory), client: 172.16.0.10, server: localhost, request: "GET /favicon.ico HTTP/1.1", host: "172.16.2.14:32768", referrer: "http://172.16.2.14:32768/" 172.16.0.10 - - [14/Jun/2018:08:06:29 +0000] "GET /favicon.ico HTTP/1.1" 404 571 "http://172.16.2.14:32768/" "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.181 Safari/537.36" "-"
映射所有接口地址
docker run -d -p HostPort:ContainerPort nginx
例如:
docker run -d -p 80:80 nginx
映射到指定地址的指定端口
docker run -d -p IP:HostPort:ContainerPort nginx
例如:
docker run -d -p 127.0.0.1:80:80 nginx
映射到指定地址的任意端口
docker run -d -p IP::ContainerPort
即HostPort留空,例如:
docker run -d -p 127.0.0.1::80 nginx
docker port查看当前映射的端口配置
docker port cd54a3d0c689 80/tcp -> 0.0.0.0:32768
80/tcp 是指容器的tcp80端口,0.0.0.0:32768是指本机的所有地址监听在32768端口
--link: 容器互联
创建一个mysql容器
docker run -d --name mysql -e MYSQL_ROOT_PASSWORD=123456 mysql:latest
创建一个web容器,并将它连接到mysql
docker run -dit --name web --link mysql:mysql busybox
连接到web容器,telnet mysql端口3306,测试是否能通
# docker exec -it web sh / # telnet mysql:3306 J 8.0.11 6rmXK*i
可以看到telnet端口是通的
查看/etc/hosts文件
127.0.0.1 localhost ::1 localhost ip6-localhost ip6-loopback fe00::0 ip6-localnet ff00::0 ip6-mcastprefix ff02::1 ip6-allnodes ff02::2 ip6-allrouters 192.168.0.4 mysql 6758c7045f5e 192.168.0.6 9d0f9a0f5862
web容器使用容器ID作为主机名,IP是192.168.0.6
mysql也使用容器ID作为主机名,IP是192.168.0.4