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
Commit the encrypted .env file, but never commit or copy .env.keys into the image.
.env.keys

2. Add dotenvx to your image

Install dotenvx in the image that runs your application.
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.
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