Next.js Discord

Discord Forum

Unable to connect to my backend api in Docker.

Answered
West Siberian Laika posted this in #help-forum
Open in Discord
Avatar
West Siberian LaikaOP
I'm running Nextjs(v15) with another backend server that serves backend stuff like JSON data and I'm unable to reach that backend after I containerize and compose everything.
This is next.config.ts:
import type { NextConfig } from "next";

const nextConfig: NextConfig = {
  output: "standalone",
  reactStrictMode: true,
  env: {
    NEXT_PUBLIC_API_URL:
      process.env.NEXT_PUBLIC_API_URL || "http://localhost:4000",
  },
  async rewrites() {
    const apiUrl = process.env.NEXT_PUBLIC_API_URL || "http://localhost:4000";
    return [
      {
        source: "/api/:path*",
        destination: `${apiUrl}/api/:path*`,
      },
    ];
  },

  async headers() {
    return [
      {
        source: "/api/:path*",
        headers: [
          { key: "Access-Control-Allow-Origin", value: "*" },
          {
            key: "Access-Control-Allow-Methods",
            value: "GET,POST,PUT,DELETE,OPTIONS",
          },
        ],
      },
    ];
  },
};

export default nextConfig;


And this is the docker file for my frontend:
FROM node:18-alpine AS builder

WORKDIR /app

COPY package.json package-lock.json ./
RUN npm ci

COPY . .

RUN npm run build

FROM node:18-alpine AS runner

WORKDIR /app

ENV NODE_ENV production
ENV NEXT_PUBLIC_API_URL=http://backend:4000

RUN addgroup -g 1001 -S nodejs
RUN adduser -S nextjs -u 1001

COPY --from=builder --chown=nextjs:nodejs /app/public ./public
COPY --from=builder --chown=nextjs:nodejs /app/.next/standalone ./
COPY --from=builder --chown=nextjs:nodejs /app/.next/static ./.next/static

USER nextjs

EXPOSE 3000

# Start command
CMD ["node", "server.js"]
Answered by West Siberian Laika
Apparently, Nextjs parses env variables at build time, not runtime.
Solution to have two env files: .env.local for local development and .env.production for production.
View full answer

1 Reply

Avatar
West Siberian LaikaOP
Apparently, Nextjs parses env variables at build time, not runtime.
Solution to have two env files: .env.local for local development and .env.production for production.
Answer