Docker 与 K8S学习笔记(十)—— 容器的端口映射

我们一般将应用部署在容器里面,而一个服务器上会有许许多多的容器,那么外界该如何访问我们的应用呢?答案是:端口映射。

Docker可以将容器对外提供服务的端口映射到host的某个端口上,外网通过此端口访问容器,要开启此功能,容器在启动时需要通过-p参数指定映射的端口号。

$ sudo docker run -d -p 80 nginx
0627d4b5aefe03d4d99a92b559d3e58d789c006961722178c9f1e94f0f270492
$ sudo docker ps
CONTAINER ID   IMAGE     COMMAND                  CREATED         STATUS         PORTS                                     NAMES
0627d4b5aefe   nginx     "/docker-entrypoint.…"   9 seconds ago   Up 8 seconds   0.0.0.0:49153->80/tcp, :::49153->80/tcp   stupefied_brahmagupta
$ curl 127.0.0.1:49153
<!DOCTYPE html>
<html>
<head>
<title>Welcome to nginx!</title>
<style>
html { color-scheme: light dark; }
body { width: 35em; margin: 0 auto;
font-family: Tahoma, Verdana, Arial, sans-serif; }
</style>
</head>
<body>
<h1>Welcome to nginx!</h1>
<p>If you see this page, the nginx web server is successfully installed and
working. Further configuration is required.</p>

<p>For online documentation and support please refer to
<a href="http://nginx.org/">nginx.org</a>.<br/>
Commercial support is available at
<a href="http://nginx.com/">nginx.com</a>.</p>

<p><em>Thank you for using nginx.</em></p>
</body>
</html>

我们可以看到,使用-p 80参数后,docker将容器中80端口映射到host的49153端口,所以我们在host直接通过49153端口就能访问到nginx服务。

那我们能否自行指定所要映射的host的端口号呢?这也是可以的,我们只需要在-p参数中将host的端口也指定上就可以了:

$ sudo docker run -d -p 8080:80 nginx
13cd7862e4d74238599e9321e897ea03cf2c01f837202bb4363ea48d052c850e
$ sudo docker ps
CONTAINER ID   IMAGE     COMMAND                  CREATED         STATUS         PORTS                                   NAMES
13cd7862e4d7   nginx     "/docker-entrypoint.…"   9 seconds ago   Up 7 seconds   0.0.0.0:8080->80/tcp, :::8080->80/tcp   kind_kirch
$ curl 127.0.0.1:8080
<!DOCTYPE html>
<html>
<head>
<title>Welcome to nginx!</title>
<style>
html { color-scheme: light dark; }
body { width: 35em; margin: 0 auto;
font-family: Tahoma, Verdana, Arial, sans-serif; }
</style>
</head>
<body>
<h1>Welcome to nginx!</h1>
<p>If you see this page, the nginx web server is successfully installed and
working. Further configuration is required.</p>

<p>For online documentation and support please refer to
<a href="http://nginx.org/">nginx.org</a>.<br/>
Commercial support is available at
<a href="http://nginx.com/">nginx.com</a>.</p>

<p><em>Thank you for using nginx.</em></p>
</body>
</html>

 

posted @ 2021-12-21 17:06  阿拉懒神灯  阅读(1362)  评论(0编辑  收藏  举报