Exposing ports with Dockerfiles

Intermediate Docker

Mike Metzger

Data Engineer

Exposing services

  • EXPOSE command
  • Defines which ports the container will use at runtime
  • Can be defined as <number>, <number>/tcp, or <number>/udp
    • Such as EXPOSE 80 or EXPOSE 80/tcp
  • Multiple entries permitted
  • Used as a documentation method
Intermediate Docker

Using the -p / -P flags

  • Still requires use of -p or -P options to docker run to make the ports available outside the container
  • The -P option will automatically map an ephemeral port to the exposed port(s). Must use docker ps -a to see which ports are mapped.
  • Using -p<host port>:<container port> allows use of specific ports.
Intermediate Docker

EXPOSE example

# Dockerfile
FROM python:3.11-slim
ENTRYPOINT ["python","-mhttp.server"]
# Let the Docker engine know 
# port 8000 should be available
EXPOSE 8000
  • Create a container from the image
    docker run pyserver
    
  • Print the state of the container
    docker ps -a
    
CONTAINER ID   IMAGE         ...   PORTS      NAMES
8c3d320255ae   pyserver      ...   8000/tcp   angry_chaum
Intermediate Docker

Making ports reachable

  • Automatically map temporary port from host to the container
    docker run -P pyserver
    
docker ps -a
CONTAINER ID   IMAGE      ...   PORTS                     NAMES
6bb458ef25da   pyserver   ...   0.0.0.0:55001->8000/tcp   beautiful_lamarr
Intermediate Docker

Finding exposed ports

  • docker inspect provides a lot of information
    docker inspect <id>
    
"NetworkSettings": {
  "Bridge": "",
  "Ports": {
    "8000/tcp": [{
                   "HostIp": "0.0.0.0",
                   "HostPort": "55001"
                    }]
            },
...
Intermediate Docker

Let's practice!

Intermediate Docker

Preparing Video For Download...