1. 程式人生 > 其它 >Docker 與 K8S學習筆記(十)—— 容器的埠對映

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>