Docker-compose pass environment variable to docker container and into npm start

Having spent far too long on this, and read copious reference material on docker and many many stack overflow articles I have to admit defeat and ask the panel for help

What I want to achieve is to have my NODE_ENV defined somewhere outside of the docker files so it can be .gitignored.

So I want to be able to have a .env file in the same top level directory along with docker-compose.yml and Dockerfile that contains an entry for NODE_ENV.

Sounds pretty straight forward?

Firstly I had problems with the CMD statement in the dockerfile. Having researched it, I find that I need to do something like this

FROM node:latest

ENV NODE_ENV=development

WORKDIR /usr/src/app

COPY ./package*.json /usr/src/app/

RUN npm install

ADD . .

CMD ["sh", "-c", "npm run start:${NODE_ENV}"]

EXPOSE 3001

It works like a charm then I run it from the command line with

docker run -e "NODE_ENV=development" .

However, bring docker-compose into the equation and it all goes wrong. And it doesn't give much in the way of errors either.

version: '3'
services:
  app:
    build: .
    environment: 
      - NODE_ENV=$NODE_ENV 
    ports:
      - '80:3001'
    links:
      - mongodb
  mongodb:
    image: mongo
    ports:
      - '27017:27017'

Now if I run this using docker-compose config I can see that the environment variable is being correctly set

services:
  app:
    build:
      context: /home/me/myproject
    environment:
      NODE_ENV: development
    links:
    - mongodb
    ports:
    - 80:3001/tcp
  mongodb:
    image: mongo
    ports:
    - 27017:27017/tcp
version: '3.0'

So my question is basically, can anyone spot what I am doing wrong? Or is this a bug in docker that I should report?

The only clues given from the logs is

app_1 exited with code 2

and in the container log

/bin/sh: 1: [: npm run ,: unexpected operator

Upvotes: 0

Views: 1090

Answers (1)

I got it working by putting the environment variable line in the docker-compose in double quotes.

version: '3'
services:
  app:
    build: .
    environment: 
      - "NODE_ENV=$NODE_ENV" 
    ports:
      - '80:3001'
    links:
      - mongodb
  mongodb:
    image: mongo
    ports:
      - '27017:27017'

Upvotes: 2

Related Questions