React/Next.js docker build failing when trying to reach out to local NEXT_PUBLIC URL

  alpine, docker, next.js, node.js, reactjs

I cannot seem to get my node:alpine Docker image for a react/next.js to build.

I can get it to build fine locally, but I never see the traffic in my API logs when the Docker build reaches out to the NEXT_PUBLIC_API_URL URL, which is itself running in a Docker container (nginx, headless craft cms, etc.).

The build does not seem to like localhost at all, as I’ve tried:


…and this is the message I get in the logs:

#15 13.76 > Build error occurred
#15 13.76 FetchError: request to http://localhost:9000/api failed, reason: connect ECONNREFUSED

I’ve heard that I can use the hostname in place of "localhost", so in my MacOS terminal I’ve typed "hostname" and I’ve swapped out the localhost for this value. This doesn’t outright error out, but the build hangs on the "Generating pages…" step of the build.

How can I get the Docker build to recognize localhost, or put another way, how can I set my NEXT_PUBLIC_API_URL to an endpoint hosted by a local Docker container?

Here is my Dockerfile:

# Install dependencies only when needed
FROM node:alpine AS deps
RUN apk add --no-cache libc6-compat
COPY package.json yarn.lock ./
RUN yarn --frozen-lockfile

# Rebuild the source code only when needed
FROM node:alpine AS builder

COPY . .
COPY --from=deps /app/node_modules ./node_modules
RUN yarn static

# Production image, copy all the files and run next
FROM node:alpine AS runner

ENV NODE_ENV production

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

# You only need to copy next.config.js if you are NOT using the default configuration
COPY --from=builder /app/public ./public
COPY --from=builder --chown=nextjs:nodejs /app/.next ./.next
COPY --from=builder /app/node_modules ./node_modules
COPY --from=builder /app/package.json ./package.json

USER nextjs


# Next.js collects completely anonymous telemetry data about general usage.
# Learn more here:
# Uncomment the following line in case you want to disable telemetry.

CMD ["yarn", "start"]

Source: Docker Questions