nirvair
nirvair

Reputation: 4180

docker env variable shows undefined

Here's my docker-compose

version: '2'
services:
  weather-cities:
    build:
      context: .
    volumes:
      - .:/usr/app
      - /usr/app/node_modules/
    ports:
      - "8080:8080"

    # Set environment variables from this file
    # env_file:
    #   - .env

    # Overwrite any env var defined in .env file (if required)
    environment:
      - DB_NAME=test
      - DB_PORT=5432
      - DB_HOST=postgres
      - DB_USERNAME=test
      - DB_PASSWORD=challenge
      - APP_PORT=8080

    links:
      - postgres

  postgres:
    image: "postgres:9.4.11"
    ports:
      - "5432:5432"
    environment:
      - POSTGRES_USER=test
      - POSTGRES_PASSWORD=challenge

Running this migration script

"db:migrate": "./node_modules/.bin/sequelize --migrations-path=migrations --models-path=models --config=config/config.js db:migrate"

And here's my Dockerfile

FROM node:8.10.0

WORKDIR /usr/app

COPY package.json .
RUN npm install --quiet

COPY . .

RUN npm run db:migrate
RUN npm run db:seed

EXPOSE 8080

CMD ["npm", "start"]

Output:

Loaded configuration file "config/config.js". Using environment "development".

ERROR: connect ECONNREFUSED 127.0.0.1:5432

config.js

let config = {
  "development": {
    "username": process.env.DB_USERNAME,
    "password": process.env.DB_PASSWORD,
    "database": process.env.DB_NAME,
    "host": process.env.DB_HOST,
    "dialect": "postgres",
    "port": process.env.DB_PORT
  }
};

module.exports = config;

Upvotes: 2

Views: 4153

Answers (1)

β.εηοιτ.βε
β.εηοιτ.βε

Reputation: 39244

When you run docker-compose up, two things happen behind the scene:

  1. docker-compose build - the images are either build from the specified Dockerfile and context, either pulled from docker images repository.
  2. docker-compose start - the containers are started out of the images for the services

During the build phase, none of your container are up and running yet.
This is what causes your actual issue, you expect, in your node build, the postgress container to be up, running and listening to the port 5432, which will never be true, because the container start phase will not happen before all the images are build.

What you are seeking to achieve can be done via entrypoint though.

Upvotes: 1

Related Questions