36

Does declaring on a docker-compose.yml:

ports:
 - "3306:3306"

and on Dockerfile:

EXPOSE 3306

have the same effect?

Victor Basso
  • 5,556
  • 5
  • 42
  • 60

1 Answers1

48

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.

jnns
  • 5,148
  • 4
  • 47
  • 74
VonC
  • 1,262,500
  • 529
  • 4,410
  • 5,250
  • 1
    Docker updated the documentation and now it is very clear: https://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). – Rot-man Apr 07 '18 at 15:17
  • 1
    @RotemJackoby I agree. I was reminded of that specification in https://stackoverflow.com/a/35414537/6309. – VonC Apr 07 '18 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 '18 at 14:40
  • 3
    @Frondor No: see the "as comment" section at the beginnig of the answer https://stackoverflow.com/a/35414537/6309 – VonC May 15 '18 at 14:48