What is the difference between docker-compose ports vs expose
According to the docker-compose reference,
Ports is defined as:
Expose ports. Either specify both ports (HOST:CONTAINER), or just the container port (a random host port will be chosen).
- Ports mentioned in docker-compose.yml will be shared among different services started by the docker-compose.
- Ports will be exposed to the host machine to a random port or a given port.
My docker-compose.yml
looks like:
mysql: image: mysql:5.7 ports: - "3306"
If I do docker-compose ps
, it will look like:
Name Command State Ports------------------------------------------------------------------------------------- mysql_1 docker-entrypoint.sh mysqld Up 0.0.0.0:32769->3306/tcp
Expose is defined as:
Expose ports without publishing them to the host machine - they’ll only be accessible to linked services. Only the internal port can be specified.
Ports are not exposed to host machines, only exposed to other services.
mysql: image: mysql:5.7 expose: - "3306"
If I do docker-compose ps
, it will look like:
Name Command State Ports--------------------------------------------------------------- mysql_1 docker-entrypoint.sh mysqld Up 3306/tcp
Edit
In recent versions of Dockerfile, EXPOSE
doesn't have any operational impact anymore, it is just informative. (see also)
ports:
- Activates the container to listen for specified port(s) from the world outside of the docker(can be same host machine or a different machine) AND also accessible world inside docker.
- More than one port can be specified (that's is why ports not port)
expose:
- Activates container to listen for a specific port only from the world inside of docker AND not accessible world outside of the docker.
- More than one port can be specified
PortsThis section is used to define the mapping between the host server and Docker container.
ports: - 10005:80
It means the application running inside the container is exposed at port 80. But external system/entity cannot access it, so it need to be mapped to host server port.
Note: you have to open the host port 10005 and modify firewall rules to allow external entities to access the application.
They can use
http://{host IP}:10005
something like this
EXPOSEThis is exclusively used to define the port on which application is running inside the docker container.
You can define it in dockerfile as well. Generally, it is good and widely used practice to define EXPOSE inside dockerfile because very rarely anyone run them on other port than default 80 port