Dockerfile by Example: Port Exposure Definition
The EXPOSE instruction documents which ports the container listens on. This code example shows how to define ports and protocols for documentation and linking.
Code
FROM nginx:alpine
# 1. Expose a single port (TCP is default)
EXPOSE 80
# 2. Expose multiple ports
EXPOSE 443 8080
# 3. Specify protocol (UDP/TCP)
EXPOSE 53/udp
EXPOSE 53/tcp
CMD ["nginx", "-g", "daemon off;"]Explanation
The EXPOSE instruction functions primarily as documentation, informing users and tools about the network ports the application listens on. Crucially, EXPOSE does not publish the port to the host machine. Publishing ports requires explicit mapping using the -p flag with docker run or the ports section in Docker Compose. Without this mapping, exposed ports are inaccessible from outside the Docker host.
Facts about EXPOSE:
- Serves as metadata for image consumers and tools
- Does not automatically publish ports to the host
- Enables the
-Pflag to publish all exposed ports to random high ports - Supports specifying protocols like
53/udp(defaults to TCP)
While not strictly required for port mapping, declaring EXPOSE is a best practice for image maintainability. It allows the -P (uppercase) flag to automatically map all exposed ports to random ephemeral ports on the host, which is useful for testing. It also helps developers understand the networking requirements of the containerized application without inspecting the source code.
Code Breakdown
EXPOSE 80 documents standard HTTP port usage.EXPOSE 443 8080 shows multiple ports can be listed.EXPOSE 53/udp specifies UDP protocol, essential for DNS services.CMD runs Nginx, which will listen on the exposed ports.
