外部访问容器

随机映射

  • -P: Docker 会随机映射一个 49000~49900 的端口到内部容器开放的网络端口。
  1. # http1.js
  2. var http = require('http');
  3. http.createServer(function (request, response) {
  4. // 发送 HTTP 头部
  5. // HTTP 状态值: 200 : OK
  6. // 内容类型: text/plain
  7. response.writeHead(200, {'Content-Type': 'text/plain'});
  8. // 发送响应数据 "Hello World"
  9. response.end('Hello World\n');
  10. }).listen(3000);
  11. // 终端打印如下信息
  12. console.log('Server running at http://127.0.0.1:3000/');
  13. # Dockerfile
  14. FROM node
  15. ENV APP_HOME /usr/src/app
  16. COPY http1.js ${APP_HOME}/index.js
  17. EXPOSE 3000
  18. WORKDIR ${APP_HOME}
  19. CMD ["node","index"]
  20. # 打包
  21. docker build -t node_http:v5 .
  22. # 运行
  23. docker run -d -P node_http:v5
  24. # 查看
  25. docker container ls
  26. CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
  27. 7f0dbe8702f0 node_http:v5 "docker-entrypoint.s…" 4 seconds ago Up 3 seconds 0.0.0.0:32768->3000/tcp naughty_panini

指定映射

  • -p参数,支持的格式如下:
  1. # 映射所有地址 hostPort:containerPort
  2. docker run -d -p 5000:5000 training/webapp python app.py
  3. # 映射到指定地址的指定端口 ip:hostPort:containerPort
  4. docker run -d -p 127.0.0.1:5000:5000 training/webapp python app.py
  5. # 映射到指定地址的任意端口 ip::containerPort
  6. docker run -d -p 127.0.0.1::5000 training/webapp python app.py
  7. # 使用 udp 标记来指定 udp 端口
  8. docker run -d -p 127.0.0.1:5000:5000/udp training/webapp python app.py
  • 注意
    • 容器有自己的内部网络和 ip 地址(使用 docker inspect 可以获取所有的变量,Docker 还可以有一个可变的网络配置。)
    • -p 标记可以多次使用来绑定多个端口: docker run -d -p 5000:5000 -p 3000:80 training/webapp python app.py

容器互联

自定义docker网络

  1. # 新建一个自定义网络,-d 参数可选 bridge overlay(用于swarm mode)
  2. docker network create -d bridge my-net
  3. # 启动容器1 加入网络
  4. docker run -dit --name ubuntu1 --network my-net ubuntu:18.04
  5. # 启动容器2加入网络
  6. docker run -dit --name ubuntu2 --network my-net ubuntu:18.04
  7. # 查看
  8. docker container ls
  9. CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
  10. 275a6b755dd7 ubuntu:18.04 "/bin/bash" 7 seconds ago Up 6 seconds ubuntu2
  11. e38afaf0e4ee ubuntu:18.04 "/bin/bash" 15 seconds ago Up 13 seconds ubuntu1
  12. # 进入容器2
  13. docker attach 275a6b755dd7
  14. # 需先安排ping
  15. apt-get update && apt-get install inetutils-ping
  16. # PING 容器1, 可正常通信
  17. PING ubuntu1 (172.18.0.2): 56 data bytes
  18. 64 bytes from 172.18.0.2: icmp_seq=0 ttl=64 time=0.238 ms
  19. 64 bytes from 172.18.0.2: icmp_seq=1 ttl=64 time=0.244 ms
  20. 64 bytes from 172.18.0.2: icmp_seq=2 ttl=64 time=0.245 ms
  21. 64 bytes from 172.18.0.2: icmp_seq=3 ttl=64 time=0.245 ms
  22. 64 bytes from 172.18.0.2: icmp_seq=4 ttl=64 time=0.187 ms