richflow
richflow

Reputation: 2144

Connect to container from another container or host using the same name

I have a docker compose file with 2 services - a database and an application service, like below. The app connects to the database using a configuration defined in an env file like below.

DATABASE_URL=postgresql://user:password1@localhost:5432/mydbname

I want to be able to connect to the db from within the application container and from the host (i.e. from outside of the containers) using the same env file.

E.g. If I run the application server from the host using the above environment variable (localhost for the db host name) it works.

However, if I run the application server from the application container I need to change the db host name in the environment variable to make it work: DATABASE_URL=postgresql://user:password1@postgresql:5432/mydbname

How can I configure docker compose such that I can use the same host in the environment variable to connect from both the host and from the application container?

docker-compose.yml

version: '3.2'

services:
  postgresql:
    image: postgres:11
    environment:
      POSTGRES_USER: user
      POSTGRES_PASSWORD: password1
    ports:
      - '5432:5432'
    volumes:
      - "/var/postgres/data/:/var/lib/postgresql/data/"

  rails-app:
    build:
      context: ./
      dockerfile: rails-dockerfile.yml
    image: rails-app:0.1
    links:
      - postgresql
    volumes:
      - type: bind
        source: ./
        target: /app
    ports:
      - '3000:3000'
    env_file: .env

volumes:
  vol-postgres:

Upvotes: 1

Views: 525

Answers (1)

Mihai
Mihai

Reputation: 10727

You cannot configure your containers for something like that, but you can configure your host.

If you are on Linux or MacOS add an entry to /etc/hosts that maps postgresql to localhost. Something like:

127.0.0.1  localhost postgresql

There is a similar file in Windows.

Then you can only use the environment variable pointing to postgresql.

However note that giving direct access from the host to your database container is a bad practise. Use it only if there is no better solution.

Upvotes: 2

Related Questions