Docker中的Next.js应用程序侦听错误的接口

w9apscun  于 2023-10-18  发布在  Docker
关注(0)|答案(1)|浏览(98)

我有一个NextJS应用程序,需要一个MySQL数据库。我为应用程序创建一个容器,为MySQL数据库创建一个容器。
这两个容器都包含在一个docker-compose堆栈grades_web和grades_mysql中
网络:

  • sys_apps_net / 10.200.5.x -将应用程序连接到反向代理,从而连接到外部世界
  • grades_web_db / 10.200.7.x -将应用程序连接到MySQL容器

grades_web容器有两个IP

  • 10.200.7.2-关于等级_web_db
  • 10.200.5.3-在sys_apps_net上

为了启动容器,我设置HOSTNAME=0.0.0.0,所以NextJS应该监听所有的IP。该应用程序是在独立模式下构建的。
当容器启动时,它说

▲ Next.js 13.5.3
   - Local:        http://b0772d4dfb3c:3000
   - Network:      http://10.200.7.2:3000

这告诉我,应用程序只监听10.200.7.2。因此,反向代理和外部世界无法访问它。
如何让应用监听所有IP地址?
NextJS 13.5.3 MySQL 8.1 Docker 24.0.6

Dockerfile

FROM node:20-alpine AS dependencies

WORKDIR /app
COPY package.json package-lock.json ./
RUN npm install

FROM node:20-alpine AS build
WORKDIR /app

COPY --from=dependencies /app/node_modules ./node_modules
COPY . .

RUN npx prisma generate
RUN npx next telemetry disable
RUN npm run build

FROM node:20-alpine AS deploy
WORKDIR /app
ENV NODE_ENV production

COPY --from=build /app/public ./public
COPY --from=build /app/package.json ./package.json
COPY --from=build /app/.next/standalone ./
COPY --from=build /app/.next/static ./.next/static
COPY --from=build /app/prisma ./prisma

EXPOSE 3000
ENV PORT 3000

CMD ["npm", "run", "start:migrate:prod"]

*docker-compose.yml

version: '3'
services:
  app:
    image: gdr.htl-villach.at/htl-it/htl-it-docker-registry/grades:0.9
    container_name: grades_web
    restart: unless-stopped

    networks: 
      - sys_apps_net
      - web_db

    environment:
      HOST: 0.0.0.0
      DATABASE_URL: ${DATABASE_URL}
      NEXTAUTH_URL: ${NEXTAUTH_URL}
      NEXTAUTH_SECRET: ${NEXTAUTH_SECRET}
      AZURE_CLIENT_ID: ${AZURE_CLIENT_ID}
      AZURE_CLIENT_SECRET: ${AZURE_CLIENT_SECRET}
      AZURE_TENANT_ID: ${AZURE_TENANT_ID}

  db:
    image: mysql:8.1
    container_name: grades_mysql
    restart: unless-stopped

    networks: 
      - web_db

    volumes:
      - mysql_data:/var/lib/mysql

    environment:
      MYSQL_ROOT_PASSWORD: ${MYSQL_ROOT_PASSWORD}
      MYSQL_DATABASE: ${MYSQL_DATABASE}
      MYSQL_USER: ${MYSQL_USER}
      MYSQL_PASSWORD: ${MYSQL_PASSWORD}
      MYSQL_ROOT_HOST: ${MYSQL_ROOT_HOST}

volumes:
  mysql_data:

networks:
  web_db:
    external: false
  sys_apps_net:
    external: true

package.json

...
 "scripts": {
   ...
   "start:migrate:prod": "HOSTNAME=0.0.0.0 npx prisma migrate deploy && node prisma/seed.mjs && node server.js"
  },
moiiocjp

moiiocjp1#

经验往往是在需要之后才出现的。
罪魁祸首是启动脚本:将HOSTNAME=0.0.0.0

"start:migrate:prod": "HOSTNAME=0.0.0.0 npx prisma migrate deploy && node prisma/seed.mjs && node server.js"

"start:migrate:prod": "npx prisma migrate deploy && node prisma/seed.mjs && HOSTNAME=0.0.0.0 node server.js"

server.js将很高兴地拿起HOSTNAME,启动日志将告诉我们:

▲ Next.js 13.5.3
   - Local:        http://localhost:3000
   - Network:      http://0.0.0.0:3000

相关问题