Detailed explanation of the difference between docker compose ports and expose

  • 2021-07-22 12:08:45
  • OfStack

There are two ways in docker-compose to expose a container's port: ports and expose.

ports

ports exposes container ports to any port or specified port of the host. Usage:


ports:
 
- "80:80" #  Object of the binding container 80 Port to host 80 Port 
 
- "9000:8080" #  Object of the binding container 8080 Port to host 9000 Port 
 
- "443" #  Object of the binding container 443 Port to any port of the host, and the bound host port number is randomly assigned when the container starts 

Using ports exposes the port to the host regardless of whether the host port is specified or not.

Container can run a number of network applications, for external access to these applications, you can through-P (uppercase) or-p (lowercase) parameters to specify port mapping.

(1) When the-P tag is used, Docker randomly maps a port from 49000 to 49900 to a network port open to the internal container.

Using docker ps, you can see that 49155 of the local host is mapped to port 5000 of the container. At this time, you can access the interface provided by web application in the container by visiting port 49155 of this machine.


$ sudo docker run -d -P training/webapp python app.py
 
$ sudo docker ps -l
 
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
 
bc533791f3f5 training/webapp:latest python app.py 5 seconds ago Up 2 seconds 0.0.0.0:49155->5000/tcp nostalgic_morse

Likewise, the application information can be viewed through the docker logs command.


$ sudo docker logs -f nostalgic_morse
 
* Running on http://0.0.0.0:5000/
 
10.0.2.2 - - [23/May/2014 20:16:31] "GET / HTTP/1.1" 200 -
 
10.0.2.2 - - [23/May/2014 20:16:31] "GET /favicon.ico HTTP/1.1" 404 - 

(2)-p (lowercase) can specify the IP and port to be mapped, but only one container can be bound to one specified port. The supported formats are hostPort: containerPort, ip: hostPort: containerPort, ip:: containerPort.

expose

expose exposes the container to link to the container of the current container, usage:


expose:
- "3000"
- "8000"

The above instruction exposes ports 3000 and 8000 of the current container to the container of link to this container.

The difference between expose and ports is that expose does not expose the port to the host.


Related articles: