从外部访问容器
指定容器端口随机映射主机端口
[[email protected] /]$ docker run -p 8080 -d --name web tomcat /bin/bash -c /root/apache-tomcat-7.0.70/bin/startup.sh 56aff84e42df074c4941a8a373305ffbba121bd4b190f58ec5c6136d062b557f [[email protected] /]$ docker port 56 8080/tcp -> 0.0.0.0:32772
访问http://192.168.0.80:32772,即可访问到容器中对应的8080端口。
使用-P随机映射容器内开放的端口
[[email protected] /]$ docker run -P --name db -e MYSQL_ROOT_PASSWORD=root -d mysql 49b1c8ba70db137107ba79950854c1b758d0c4dc8f4ac16425cde73a648631f8 [[email protected] /]$ docker ps -l CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES 49b1c8ba70db mysql "docker-entrypoint.s 4 seconds ago Up 4 seconds 0.0.0.0:32773->3306/tcp db
指定主机端口映射,主机端口:容器端口
[[email protected] /]$ docker run -p 8090:8080 -d --name web1 tomcat /bin/bash -c /root/apache-tomcat-7.0.70/bin/startup.sh c2fa3f78eb52f5e45af1bb578b0a892829611175722ea0909fc890edd1347a23 [[email protected] /]$ docker port web1 8080/tcp -> 0.0.0.0:8090
访问:http://192.168.0.80:8090即可访问到容器中对应的8080端口。
容器的互联
实现db容器和web容器的互联
创建db容器
[[email protected] /]$ docker run --name db -e MYSQL_ROOT_PASSWORD=root -d mysql
创建一个web容器,并将它连接到db
[[email protected] /]$ docker run -d -P --name web --link db:db tomcat a0c6eded53622dc71e54892eb63d5d94b1e1ce2882d307b2de8b6dd23e0c865d [[email protected] /]$ docker exec -it web /bin/bash [[email protected] /]# env HOSTNAME=a0c6eded5362 DB_NAME=/web/db DB_PORT=tcp://172.17.0.76:3306 DB_PORT_3306_TCP_PORT=3306 DB_ENV_GOSU_VERSION=1.7 LS_COLORS= DB_PORT_3306_TCP_PROTO=tcp DB_ENV_MYSQL_ROOT_PASSWORD=root PATH=/root/jdk1.7.0_80/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin PWD=/ JAVA_HOME=/root/jdk1.7.0_80 DB_PORT_3306_TCP_ADDR=172.17.0.76 SHLVL=1 HOME=/root DB_PORT_3306_TCP=tcp://172.17.0.76:3306 DB_ENV_MYSQL_VERSION=5.7.14-1debian8 DB_ENV_MYSQL_MAJOR=5.7 _=/usr/bin/env [[email protected] /]# cat /etc/hosts 172.17.0.79 a0c6eded5362 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 172.17.0.76 db c456ffdefca6 [[email protected] /]# ping db PING db (172.17.0.76) 56(84) bytes of data. 64 bytes from db (172.17.0.76): icmp_seq=1 ttl=64 time=0.095 ms 64 bytes from db (172.17.0.76): icmp_seq=2 ttl=64 time=0.070 ms 64 bytes from db (172.17.0.76): icmp_seq=3 ttl=64 time=0.070 ms
--link name:alias name为容器名,alias为容器连接的别名。
时间: 2024-11-03 22:29:38