I am wondering what is the difference between using EXPOSE
in a Dockerfile and in a Docker-Compose file?
What if it is declared in one file and not the other? Or what if it is declared in both but with different port numbers?
With using "expose" you define communication within the network. If you want to expose the default ports you don't need to define "expose" in your docker-compose file.
The expose section allows us to expose specific ports from our container only to other services on the same network. We can do this simply by specifying the container ports. The ports section also exposes specified ports from containers.
The key difference between the Dockerfile and docker-compose is that the Dockerfile describes how to build Docker images, while docker-compose is used to run Docker containers.
The EXPOSE instruction informs Docker that the container listens on the specified network ports at runtime. You can specify whether the port listens on TCP or UDP, and the default is TCP if the protocol is not specified.
Docker compose uses the Dockerfile if you add the build command to your project's docker-compose. yml. Your Docker workflow should be to build a suitable Dockerfile for each image you wish to create, then use compose to assemble the images using the build command.
EXPOSE in Dockerfile
is a just a metadata information. Which tells docker when someone uses docker run -P
which ports need to be Exposed.
Using them in compose or docker run is a dynamic way of specifying these ports. So an image like nginx
or apache
which is always supposed to run on port 80 inside the container will use EXPOSE
in Dockerfile itself.
While an image which has dynamic port which may be controlled using an environment variable will then use expose in docker run
or compose file
docker run -e UI_PORT=5556 --expose 5556 -P ....
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With