3.9 Ports

The same as with volumes, but with ports, they are used to enable Internet services.

Syntax: --publish/-p host:container

In the example below we use NGINX, a popular web server that, by default, exposes the port 80.

# We start the web server in the background
docker run --detach --name webserver nginx

# We test with curl if port 80 is available from our host machine
curl localhost:80

# We then check inside the container
docker exec webserver curl localhost:80

# We remove the container
docker rm -f webserver
# We start the web server in the background. We use **publish** to map the ports from the container to the host
docker run --detach --name webserver --publish 80:80 nginx

# We test if port 80 is available from our host machine
curl localhost:80

# We remove the container
docker rm -f webserver
# We start the web server in the background. We use **publish** to map the ports from the container to the host. Now instead of mapping to 80 in the host, we map to another one (3838 for instance).
docker run --detach --name webserver -p 3838:80 nginx

# We test if port 80 is available from our host machine
curl localhost:80

# We test if the different mapped port is available from our host machine
curl localhost:3838

# We repeat the check, but now inside the container
docker exec webserver curl localhost:80
docker exec webserver curl localhost:3838

# We remove the container
docker rm -f webserver
You can check the website also from your web browser at: http://mymachine-address-here/ (port 80 by default). Replace your mymachine-address-here for machine provided address or 127.0.0.1/localhost in case you were trying it from your own machine.