Encrypt a .env file for Docker Compose

Encrypt a .env file for Docker Compose and inject its secrets when your service 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 in the image that runs your application.

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 . .

CMD ["node", "index.js"]

3. Run with Compose

Prepend the service command with dotenvx run -- and pass the private key through from the environment running Compose.

compose.yaml

services:
  app:
    build: .
    command: dotenvx run -- node index.js
    environment:
      DOTENV_PRIVATE_KEY: ${DOTENV_PRIVATE_KEY}

For a local check, let Compose read the private key from your ignored .env.keys file.

docker compose --env-file .env.keys up --build

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


Production

Provide DOTENV_PRIVATE_KEY through your deployment system's secret store before it starts Docker Compose. Do not put the key in the Dockerfile, image, compose.yaml, or encrypted .env file.

DOTENV_PRIVATE_KEY="$DOTENV_PRIVATE_KEY" docker compose up --build

If you encrypted a named environment file, update the service command to use the matching file and private key name. For example, use dotenvx run -f .env.production -- node index.js with DOTENV_PRIVATE_KEY_PRODUCTION.