Exposing Ports in Dockerfiles
When building Docker images, you can specify the ports that should be exposed within the container using the EXPOSE
instruction in the Dockerfile.
Syntax for Exposing Ports
The EXPOSE
instruction in a Dockerfile follows this syntax:
EXPOSE < port > [ < port > / < protocol > ...]
Here, <port>
represents the port number, and the optional <protocol>
specifies the protocol, which can be either tcp
(default) or udp
.
For example, to expose port 80 (HTTP) and port 22 (SSH) in your container, you would use the following EXPOSE
instruction:
EXPOSE 80 22
Mapping Exposed Ports at Runtime
When you run a container based on the image, you can map the exposed ports to the host machine's ports using the -p
or --publish
flag with the docker run
command.
docker run -p <host-port>:<container-port> <image-name>
For instance, to map the container's port 80 to the host's port 8080, you would use the following command:
docker run -p 8080:80 my-app
This allows external clients to access the service running on port 80 inside the container by connecting to port 8080 on the host machine.
Exposing Multiple Ports
You can expose multiple ports in a Dockerfile by using multiple EXPOSE
instructions. This is useful when your container runs multiple services or applications that need to be accessible from the host.
EXPOSE 80
EXPOSE 22
EXPOSE 3306
When running the container, you can map each of these exposed ports to the host's ports using the -p
or --publish
flag.
docker run -p 8080:80 -p 2222:22 -p 3306:3306 my-app
By following this approach, you can ensure that all the necessary ports are exposed and accessible from the host machine.