Postgres Initialize script not working Docker version 3.4

Viewed 57

Trying to dockerize an application and in my application, i have the following

docker-compose.yml

version: '3.4'

services:
  app: 
    build:
      context: .
      dockerfile: Dockerfile
    depends_on:
      - database
    ports: 
      - "3000:3000"
    volumes:
      - .:/app
      - gem_cache:/usr/local/bundle/gems
    env_file: .env
    environment:
      RAILS_ENV: development

  database:
    image: postgres:10.12
    volumes:
      - ./init.sql/:/docker-entrypoint-initdb.d/init.sql
      - db_data:/var/lib/postgresql/data

volumes:
  gem_cache:
  db_data:

In my init.sql file

CREATE USER user1 WITH PASSWORD 'password';
ALTER USER user1 WITH SUPERUSER;

i have already run chmod +x init.sql

In my .env file i have the following

DATABASE_NAME=tools_development
DATABASE_USER=user1
DATABASE_PASSWORD=password
DATABASE_HOST=database

And this is my Dockerfile

FROM ruby:2.7.0

ENV BUNDLER_VERSION=2.1.4

RUN apt-get -y update --fix-missing


RUN apt-get install -y bash git build-essential nodejs libxml2-dev openssh-server libssl-dev libreadline-dev zlib1g-dev postgresql-client libcurl4-openssl-dev libxml2-dev libpq-dev tzdata

RUN gem install bundler -v 2.1.4

WORKDIR /app

COPY Gemfile Gemfile.lock ./

RUN bundle check || bundle install 

COPY . ./ 

ENTRYPOINT ["./entrypoint.sh"]

But each time I run docker-compose run --build and try to run my application. I get error:

could not translate host name "database" to address: Name or service not known

I have tried everything possible but still the same error.

Does anyone have any idea on how to fix this issue?

I know the issue is happening because the postgres initialize scripts are not running. I have seen a lot of options online and i have tried everything but I am still facing the same error.

Any help is appreciated

Thanks

1 Answers

From the postgres docker image documentation you can see that the POSTGRES_USER and POSTGRES_PASSWORD are the necessary environment variables to setup the postgres container

You could add these environment variables to your .env file. So the file will be as follow:

.env

DATABASE_NAME=tools_development
DATABASE_USER=user1
DATABASE_PASSWORD=password
DATABASE_HOST=database

POSTGRES_USER=user1
POSTGRES_PASSWORD=password
POSTGRES_DB=tools_development

These environment variables will be used from the postgres container to init the DB and assign the user, so you can get rid of the init.sql file

After that you need to add the reference of the .env file in the database(postgres:10.12) service.
So your docker compose file should be as follow:

docker-compose.yml

...
  database:
    image: postgres:10.12
    volumes:
      - db_data:/var/lib/postgresql/data
    env_file: .env 
...
Related