Jayaram
Jayaram

Reputation: 6606

How to properly deal with .env files in docker

I have a node app using dotenv to keep track of env variables. Its using the .env file in the root folder to get the variables in runtime. The problem is when i'm using docker to build a node image the below line copies the .env file for the build as well

FROM node:latest

# Create app directory
RUN mkdir -p /usr/src/app
WORKDIR /usr/src/app

# Install app dependencies
COPY package.json /usr/src/app/
RUN npm install

# Bundle app source
COPY . /usr/src/app

EXPOSE 8000

If i build & pull the image from dockerhub. The file already contains the .env file i used in development. Ideally , i would like to specify a different .env file for production. (perhaps manually creating a new .env file in the production server)

i tried specifying the .env file in dockerignore . but line COPY . /usr/src/app still seems to copy the env file as well.

I do not need to use dotenv as such. I tried specifying it like the below

version: '2'

services:
  node:
    container_name: node
    build: .
    env_file: .env
    volumes:
      - .:/usr/src/app
      - /usr/src/app/node_modules
    command: npm start

so i really dont need to specify a .env folder in the build. But this doesnt work as well.

How do i stop the COPY command from copying the .env file?

Upvotes: 25

Views: 29437

Answers (3)

kiranr
kiranr

Reputation: 2465

create a .dockerignore file in the same directory as .env and Dockerfile then add .env file to .dockerignore file. now Docker will not include .env file while building the image.

#.dockerignore 
.env

Upvotes: 7

billkw
billkw

Reputation: 3699

There's a file for that!

Before the docker CLI sends the context to the docker daemon, it looks for a file named .dockerignore in the root directory of the context. If this file exists, the CLI modifies the context to exclude files and directories that match patterns in it. This helps to avoid unnecessarily sending large or sensitive files and directories to the daemon and potentially adding them to images using ADD or COPY.

In your case, you'll just need to echo .env >> .dockerignore while in the same directory as your Dockerfile.

Upvotes: 16

Matthew
Matthew

Reputation: 11347

Why not simply add the following?:

RUN rm /usr/src/app/.env
COPY dockerenv /usr/src/app/.env

(Also if you're worried about .env data leaking out, be aware that the old .env file is possibly visible in the file system layers. You can squash the filesystem to get rid of this).

Upvotes: -3

Related Questions