Docker端口映射

前言

在启动容器的时候,如果不指定对应的参数,在容器外部是无法通过网络来访问容器内部的网络应用和服务的。
当容器中运行一些网络应用,要让外部访问这些应用时,可以通过-p-P参数来指定端口映射。

1 随机映射

当使用-P(大写)标记时,Docker会随机映射一个端口到内部容器开放的网络端口(端口范围在 Linux 系统使用的端口之外且一般过万)。

[root@johnnyg03 ~]# docker run -it --name web1 -P nginx:latest /bin/bash
[root@johnnyg03 ~]# docker port web1 
80/tcp -> 0.0.0.0:49154
80/tcp -> :::49154
oot@8d7dd9f2147a:/# echo "hello web1" > /usr/share/nginx/html/index.html
root@8d7dd9f2147a:/# /usr/sbin/nginx
[root@johnnyg03 ~]# curl 10.0.2.12:49154
hello web1

2 映射所有地址的指定端口

[root@johnnyg03 ~]# docker run -it --name web2 -p 80:80 nginx:latest /bin/bash
[root@johnnyg03 ~]# docker port web2
80/tcp -> 0.0.0.0:80
80/tcp -> :::80
root@04194d318b91:/# echo "hello web2" > /usr/share/nginx/html/index.html
root@04194d318b91:/# /usr/sbin/nginx
[root@johnnyg03 ~]# curl 10.0.2.12:80
hello web2

3 映射指定地址的随机端口

[root@johnnyg03 ~]# docker run -it --name web3 -p 10.0.2.12::80 nginx:latest /bin/bash
[root@johnnyg03 ~]# docker port web3 
80/tcp -> 10.0.2.12:49156
root@2eadd48a48a9:/# echo "hello web3" > /usr/share/nginx/html/index.html
root@2eadd48a48a9:/# /usr/sbin/nginx
[root@johnnyg03 ~]# curl 10.0.2.12:49156
hello web3

4 映射指定地址的指定端口

[root@johnnyg03 ~]# docker run -it --name web4 -p 10.0.2.12:8080:80 nginx:latest /bin/bash
[root@johnnyg03 ~]# docker port web4 
80/tcp -> 10.0.2.12:8080
root@11d9748b81fe:/# echo "hello web4" > /usr/share/nginx/html/index.html
root@11d9748b81fe:/# /usr/sbin/nginx
[root@johnnyg03 ~]# curl 10.0.2.12:8080
hello web4
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值