0

I've built a Docker compose file to run database and a nodejs microservice in their own containers.

The database seems to stops working if I don't specify the EXPOSE ports, even though I've specified them in the compose file. Do we have to specify ports in both places?

database/Dockerfile

FROM mysql

ENV MYSQL_DATABASE=test
ENV MYSQL_ROOT_PASSWORD=password

EXPOSE 6603:3306

COPY ./schema.sql /docker-entrypoint-initdb.d/

docker-compose.yml

version: '3'

services:
  database:
    build:
      ./database
    ports:
      - "6603:3306"
    image: "test-mysql"
    container_name: "test-mysql"

  web:
    build:
      ./service
    ports:
      - "8080:8080"
    depends_on:
      - database
    image: "test-nodejs"
    container_name: "test-nodejs"
    restart: on-failure

Do I've to specify ports 6603:3306 in both Database/Dockerfile and docker-compose.yml file?

Developer
  • 924
  • 3
  • 14
  • 30
  • 1
    Check [What is the difference between “expose” and “publish” in Docker?](https://stackoverflow.com/questions/22111060/what-is-the-difference-between-expose-and-publish-in-docker/) – tgogos May 22 '19 at 10:40

3 Answers3

2

On modern Docker, EXPOSE statements are almost purely documentation. You also can't un-expose a port once it's been exposed in a Dockerfile, and the standard mysql image will already EXPOSE 3306, so you don't need an EXPOSE line in your own Dockerfile.

(In any case a Dockerfile can never specify a specific host port it wants to use, only a container-side port that should be made visible.)

David Maze
  • 130,717
  • 29
  • 175
  • 215
  • thanks, it's helpful, I've another issue as well, what should I specify in the database host in my web application (nodejs), `host: "database"` or `host: "127.0.0.1"` none of them are working actually. – Developer May 22 '19 at 10:49
0

only EXPOSE 3306 - In dockerfile which tells inside container DB running on that port.

ports: - "6603:3306"

This is perfect which tells outside container you can access DB with 6603 Port.

Akshay barahate
  • 649
  • 8
  • 23
  • the question is why specify the ports in both files, isn't one file enough? – Developer May 22 '19 at 10:41
  • You have to tell on which port your application running inside container so 1st EXPOSE in Docker in mandatory. In compose you might want to scale or map different port to that msql container. So Port mapping in compose. – Akshay barahate May 22 '19 at 10:44
  • Dockerfile is run-time application bluepriint in the form for commands. Compose is to run and manage the containers. So, 2 different entiy and hence need in both file – Akshay barahate May 22 '19 at 10:47
0

Yes it's necessary to specify the ports in file without it one will not able to expose the container port and in docker compose if you will not specify port it will not be able to make connection.

But in docker file you can do

EXPOSE 3360
Harsh Manvar
  • 27,020
  • 6
  • 48
  • 102