#Nuxt ENV not working in docker container

4 messages · Page 1 of 1 (latest)

south ginkgo
#

Hello!
I am working on a Nuxt3 project and I would like to have a docker container running it, but I'm facing some issues.

When the image is built and the container is created, the ENV variables I pass through the docker compose are not being passed to Nuxt, I can confirm this through some console logs.
What could I be doing wrong?

Dockerfile:

# Use an official node image as the base image
FROM oven/bun:1 as builder
WORKDIR /usr/src/app

# Set the working directory
WORKDIR /app

# Copy package.json
COPY package*.json ./

# Install dependencies
RUN bun i

# Copy the rest of the application files
COPY . .

# Build the application
RUN bun run build

# Use a smaller image for the production environment
FROM node:22.3.0-alpine3.20

# Set the working directory
WORKDIR /app

# Copy only the necessary files for running the application
COPY --from=builder /app/node_modules ./node_modules
COPY --from=builder /app/.output ./.output
COPY --from=builder /app/package*.json ./

# Expose the port the app runs on
EXPOSE 3000

# Command to run the application
CMD ["node", ".output/server/index.mjs"]

Docker compose:

services:
    db:
        image: postgres:15
        container_name: 'postgres_db'
        environment:
            POSTGRES_DB: spenser
            POSTGRES_USER: admin
            POSTGRES_PASSWORD: 1234
        ports:
            - 5432:5432

    app:
        build: .
        container_name: 'spenser'
        ports:
            - 3000:3000
        environment:
            JWT_SECRET: changeme
            DB_NAME: spenser
            DB_HOST: db
            DB_USER: admin
            DB_PASSWORD: 1234
            DB_PORT: 5432
        depends_on:
            - db
#

Nuxt runtime config:

runtimeConfig: {
        JWT_SECRET: process.env.JWT_SECRET as string,
        JWT_EXPIRATION: process.env.JWT_EXPIRATION || '900',
        PASSWORD_SALT_ROUNDS: process.env.PASSWORD_SALT_ROUNDS || '10',

        DB_NAME: process.env.DB_NAME,
        DB_HOST: process.env.DB_HOST,
        DB_USER: process.env.DB_USER,
        DB_PASSWORD: process.env.DB_PASSWORD,
        DB_PORT: process.env.DB_PORT || '5432',

        MAX_TRANSACTION_FILE_SIZE: Number(
            process.env.MAX_TRANSACTION_FILE_SIZE || 1024 * 1024 * 10
        ) //10 MB
    },

Use of ENV in the code:

const { DB_NAME, DB_HOST, DB_USER, DB_PASSWORD, DB_PORT } = useRuntimeConfig()
console.log(DB_NAME, DB_HOST, DB_USER, DB_PASSWORD, DB_PORT)
south ginkgo
#

I have solved the issue, documentation is not good at explaining this...

#

Envs in nuxt are read at build time and injected into the compiled solution. Thanks to the runtime config, it also has the capability of reading runtime system envs