1

My docker-compose.yml file looks like this:

version: '3.7'

networks: 
  myNetwork:

volumes:
  mongo_data:

services:

  db:
    image: mongo
    restart: always
    networks: 
      - myNetwork
    volumes: 
      - mongo_data:/data/db
    ports: 
        - "27017:27017"

  mongoExpress:
    image: mongo-express
    networks: 
      - myNetwork
    ports:
      - "8081:8081"
    environment: 
      - ME_CONFIG_MONGODB_SERVER=<db-container-name>
    depends_on: 
      - db

For mongo-express to work, I need to be able to pass it the db/mongo container name. Is there a way to achieve this with compose?

reggaemahn
  • 6,272
  • 6
  • 34
  • 59

1 Answers1

2

The service name is the host name on the network (myNetwork) created by compose.

You may use db as the host name and value for <db-container-name>

i.e.

ME_CONFIG_MONGODB_SERVER=db
DazWilkin
  • 32,823
  • 5
  • 47
  • 88
  • Thanks for the answer. How does this work? When I do a docker inspect on the container for `db` the hostname field is not `db`. It's something like `f7c3f437315a` – reggaemahn Feb 19 '20 at 04:56
  • You're welcome. You're asking a question that would require a lengthy answer and is best addressed by Docker's networking docs. Have a look here for starters: https://docs.docker.com/network/ – DazWilkin Feb 19 '20 at 05:45
  • I did read through the docs before asking the question but couldn't find anything. Would you mind pointing me to the part in that document that you're referring to? – reggaemahn Feb 20 '20 at 04:40
  • I wasn't referring to a specific section. You can enumerate the networks (`docker network ls`) and then `docker inspect ${ID}` to see which containers are bound to the network. Docker provides a DNS service (look at the `/etc/resolv.conf` in a container) and you should be able to e.g. `nslookup db` to see that this resolves to the appropriate container network subnet. HTH! – DazWilkin Feb 20 '20 at 20:38
  • Yeah, the `nslookup` definitely helps. – reggaemahn Feb 20 '20 at 22:22