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_${USER} 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_${USER} curl localhost:80
# We remove the container
docker rm -f webserver_${USER}
# 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_${USER} -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_${USER} curl localhost:80
docker exec webserver_${USER} curl localhost:3838
# We remove the container
docker rm -f webserver_${USER}
Modify 3838 port with any other port that may not be conflicting.