Encrypt a .env file for Docker

Encrypt a .env file for Docker, include it safely in your image, and inject its secrets when the container starts.

1. Encrypt

Encrypt your .env file before building the image.

$ dotenvx encrypt
◈ encrypted (.env)

Commit the encrypted .env file, but never commit or copy .env.keys into the image.

.dockerignore

.env.keys

2. Add dotenvx to your image

Install dotenvx and use dotenvx run -- as the image entrypoint. Docker appends the existing CMD, so your application command stays easy to change.

Dockerfile

FROM node:22-alpine

RUN apk add --no-cache curl \
  && curl -sfS https://dotenvx.sh | sh \
  && apk del curl

WORKDIR /app
COPY package*.json ./
RUN npm ci --omit=dev
COPY . .

ENTRYPOINT ["dotenvx", "run", "--"]
CMD ["node", "index.js"]

The same ENTRYPOINT works with other base images and application commands.

3. Run

For a local check, pass the private key from your ignored .env.keys file.

docker build -t myapp .
docker run --env-file .env.keys myapp

Dotenvx decrypts the committed .env file inside the container and injects its values only when the application starts.


Production

Provide DOTENV_PRIVATE_KEY through your deployment platform's secret store when it starts the container. Do not put the key in the Dockerfile, image, or encrypted .env file.

docker run --env DOTENV_PRIVATE_KEY="$DOTENV_PRIVATE_KEY" myapp

If you encrypted a named environment file, pass the matching file and private key name. For example, use dotenvx run -f .env.production -- with DOTENV_PRIVATE_KEY_PRODUCTION.