【发布时间】:2020-12-16 21:43:57
【问题描述】:
我有一个希望使用 Docker 和 nginx 运行的 nextjs 项目。
我希望使用在后台连接nextjs的nginx(只有nginx可以与nextjs对话,用户需要与nginx对话才能与nextjs对话)。
假设它是标准的nextjs项目结构和dockerfile内容(如下提供),有没有办法在docker中使用nginx和nextjs?
我知道我可以使用 Docker-compose。但我想把它放在一个 docker 图像下。由于我打算将图像推送到 heroku 虚拟主机。
注意:我正在使用服务器端渲染
码头文件
# Base on offical Node.js Alpine image
FROM node:latest as builder
# Set working directory
WORKDIR /usr/app
# install node-prune (https://github.com/tj/node-prune)
RUN curl -sfL https://install.goreleaser.com/github.com/tj/node-prune.sh | bash -s -- -b /usr/local/bin
# Copy package.json and package-lock.json before other files
# Utilise Docker cache to save re-installing dependencies if unchanged
COPY package.json ./
COPY yarn.lock ./
# Install dependencies
RUN yarn install --frozen-lockfile
# Copy all files
COPY ./ ./
# Build app
RUN yarn build
# remove development dependencies
RUN yarn install --production
# run node prune. Reduce node_modules size
RUN /usr/local/bin/node-prune
#######################################################
FROM node:alpine
WORKDIR /usr/app
# COPY package.json next.config.js .env* ./
# COPY --from=builder /usr/app/public ./public
COPY --from=builder /usr/app/.next ./.next
COPY --from=builder /usr/app/node_modules ./node_modules
EXPOSE 3000
CMD ["node_modules/.bin/next", "start"]
dockerfile 灵感来自https://github.com/vercel/next.js/blob/canary/examples/with-docker/Dockerfile.multistage
编辑:nginx default.conf
upstream nextjs_upstream {
server nextjs:3000;
# We could add additional servers here for load-balancing
}
server {
listen 80 default_server;
server_name _;
server_tokens off;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection 'upgrade';
proxy_set_header Host $host;
proxy_cache_bypass $http_upgrade;
location / {
proxy_pass http://nextjs_upstream;
}
}
【问题讨论】:
-
我不知道nextjs,但是如果它在服务器端做东西并且你想把它隐藏在nginx后面,那么让nextjs只在你不知道的内部端口上监听localhost从 docker 镜像中导出,只让 nginx 监听导出的端口并转发到内部端口。见stackoverflow.com/questions/5009324/node-js-nginx-what-now?rq=1
-
这就是我所看到的。在 3000 端口运行 NextJS,让 nginx 端口转发到 NextJS。但我不知道如何在 Docker 中做到这一点。
-
由于在上面的示例中,nginx 在端口 80 上运行,因此您必须
EXPOSE 80。然后当你运行容器时,你需要告诉 docker 将该端口 80 绑定到哪里。前任docker run -p 80:80 <image name>会告诉 docker 使暴露的端口 80(在 docker 容器上)在端口 80(在主机上)可用。