35

Does declaring on a docker-compose.yml:

ports:
 - "3306:3306"

and on Dockerfile:

EXPOSE 3306

have the same effect?

1 Answer 1

47

No: EXPOSE only opens the port in the container, making it accessible by other containers.

"3306:3306" will publish the port on the host, making the same port accessible from the host.

See Dockerfile EXPOSE:

The EXPOSE instruction informs Docker that the container listens on the specified network ports at runtime.
EXPOSE does not make the ports of the container accessible to the host. To do that, you must use the -p flag to publish a range of ports.

That is what the docker-compose.yml ports section does. It maps container port to the host.

4
  • 1
    Docker updated the documentation and now it is very clear: docs.docker.com/engine/reference/builder/#expose The EXPOSE instruction does not actually publish the port. It functions as a type of documentation between the person who builds the image and the person who runs the container, about which ports are intended to be published. To actually publish the port when running the container, use the -p flag on docker run.. Like VonC mentioned, the run -p part can be done with docker-compose.yml (the ports field).
    – RtmY
    Apr 7, 2018 at 15:17
  • 1
    @RotemJackoby I agree. I was reminded of that specification in stackoverflow.com/a/35414537/6309.
    – VonC
    Apr 7, 2018 at 15:20
  • 11
    But does that means that if I use ports: "80:80" in docker-compose, I don't need to write EXPOSE 80 in my Dockerfile, right?
    – Frondor
    May 15, 2018 at 14:40
  • 3
    @Frondor No: see the "as comment" section at the beginnig of the answer stackoverflow.com/a/35414537/6309
    – VonC
    May 15, 2018 at 14:48

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.