Docker - Expose a port

发布时间 2023-09-22 21:46:30作者: ZhangZhihuiAAA

In order to access the nginx from our workstation, we would need to expose the port 80 from within the nginx container to our workstation. Let us first stop the container and recreate it to expose the container to our workstation:

% docker stop vigorous_chebyshev
vigorous_chebyshev
% docker rm vigorous_chebyshev
vigorous_chebyshev

The next step would be to run the nginx container once more, but now, we would need to ensure we expose port 80 of our nginx container to our workstation. At the same, we can try to use the -name flag so that we can control the name of the running
container. We can provide a shorter docker container name in order to make it easier to control the container.

zzh@ZZHPC:~$ docker run -p 80:80 -d --name=test nginx
f37c663dc7058d5c470bb8f0dee20f1da9cb0add6862d3c826abc8d7d6935ffe
zzh@ZZHPC:~$ docker ps -a
CONTAINER ID   IMAGE         COMMAND                  CREATED          STATUS                   PORTS                               NAMES
f37c663dc705   nginx         "/docker-entrypoint.…"   10 seconds ago   Up 9 seconds             0.0.0.0:80->80/tcp, :::80->80/tcp   test

Note that for the ports of our running container test, it exposes port 80 to our workstation via the following CIDR combination 0.0.0.0—which accepts traffic from any source at port 80. If we are to run the curl command from our workstation, we
will get the expected response of the welcome nginx page:

zzh@ZZHPC:~$ curl localhost
<!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>

With this, we can even add localhost to any browser on our workstation to view the nginx welcome page.

 

zzh@ZZHPC:~$ docker stop test
test
zzh@ZZHPC:~$ docker rm test
test