Azoulay Jason
Azoulay Jason

Reputation: 3009

Can't set environment variables with docker run -e or --env-file option

Dockerfile

FROM node:10

# Create app directory
WORKDIR /usr/server

# Install app dependencies
# A wildcard is used to ensure both package.json AND package-lock.json are copied
# where available (npm@5+)
COPY package*.json /usr/server/

RUN npm install
# If you are building your code for production
# RUN npm ci --only=production

# Bundle app source
COPY . /usr/server/

EXPOSE 3000

CMD [ "node", "./bin/www.js" ]`

Then I run

    docker run -d -p 3000:3000 chatapp-back 
    -e DB_HOST="mongodb://localhost:27017/" 
    -e DB_USER="user" 
    -e DB_NAME="dbname" 
    -e DB_PASS="dbpass" 
    -e JWT_SECRET="my-jwt-secret"

Console output with docker logs <container-id>

[eval]:1
JWT_SECRET=my-jwt-secret
^

ReferenceError: my is not defined
    at [eval]:1:1
    at Script.runInThisContext (vm.js:122:20)
    at Object.runInThisContext (vm.js:329:38)
    at Object.<anonymous> ([eval]-wrapper:6:22)
    at Module._compile (internal/modules/cjs/loader.js:778:30)
    at evalScript (internal/bootstrap/node.js:590:27)
    at startup (internal/bootstrap/node.js:265:9)
    at bootstrapNodeJSCore (internal/bootstrap/node.js:623:3)

I also tried with docker run -d -p 3000:3000 chatapp-back --env-file .env

but console returned

node: bad option: --env-file

I'm doing something wrong here

I used docker run documentation

this article

and this article

Upvotes: 8

Views: 12764

Answers (2)

Free Palestine
Free Palestine

Reputation: 975

Your image name should come last. I was doing the same thing at first.

     docker run -d -p 3000:3000 
        -e DB_HOST="mongodb://localhost:27017/" 
        -e DB_USER="user" 
        -e DB_NAME="dbname" 
        -e DB_PASS="dbpass" 
        -e JWT_SECRET="my-jwt-secret"
        chatapp-back

Upvotes: 2

Adiii
Adiii

Reputation: 60114

Rearrange the docker run command, as the default entrypoint for node base docker image, is node, so the container considers --env-file .env as an argument to node process.

docker run -d -p 3000:3000  --env-file .env chatapp-back

Also, you can verify this before running the main process.

docker run -it -p 3000:3000 --env-file .env chatapp-back -e "console.log(process.env)"

Upvotes: 18

Related Questions