我們一般將應用部署在容器里面,而一個服務器上會有許許多多的容器,那么外界該如何訪問我們的應用呢?答案是:端口映射。
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>