In Docker Compose, the ports and expose directives are commonly used for network configuration, each serving distinct purposes regarding container networking and accessibility.
ports
The ports directive maps container ports to host ports. This enables external networks, including the host machine and external devices, to access services running within the container through the host's port. For instance, if a web application is running on port 80 within the container, you can map this port to port 8080 on the host using ports, allowing access to the application via the host's port 8080.
Example:
yamlservices: webapp: image: webapp:latest ports: - "8080:80"
In this example, port 80 inside the container is mapped to port 8080 on the host.
expose
The expose directive indicates which ports should be exposed for other containers to connect. It does not map ports to the host, meaning ports exposed with expose are accessible only by other containers within the same Docker network and cannot be accessed from external networks.
Example:
yamlservices: db: image: postgres:latest expose: - "5432"
In this example, the database service db exposes port 5432 for other services within the same Docker network, but this port is not mapped to the host and is not accessible from external networks.
Summary
In summary, ports facilitates port mapping (from container to host), enabling services to be accessed externally. expose is used solely to declare ports open for communication between containers within the same Docker network, without port mapping; its purpose is to improve container interoperability. In practice, selecting the appropriate directive based on service requirements and security considerations is essential.