NGINX is used as a reverse proxy in front of the Next.js application to handle the SSL connection (and offer an HTTPS URI).
Dockerfile
FROM node:20.10.0-alpine AS base
# Install dependencies only when needed
FROM base AS deps
RUN apk add --no-cache libc6-compat
WORKDIR /usr/src/app
# Install dependencies based on the preferred package manager
COPY package.json package-lock.json ./
RUN npm i -y
RUN rm -rf ./.next/cache
# Rebuild the source code only when needed
FROM base AS builder
WORKDIR /usr/src/app
COPY --from=deps /usr/src/app/node_modules ./node_modules
COPY . .
RUN npm run build
# Production image, copy all the files and run next
FROM base AS runner
WORKDIR /usr/src/app
RUN addgroup --system --gid 1001 nodejs
RUN adduser --system --uid 1001 nextjs
COPY --from=builder /usr/src/app/public ./public
COPY --from=builder --chown=nextjs:nodejs /usr/src/app/.next/standalone ./
COPY --from=builder --chown=nextjs:nodejs /usr/src/app/.next/static ./.next/static
USER nextjs
# EXPOSE 3000
CMD ["node", "server.js"]
next.config.js
const nextConfig = {
output: 'standalone',
reactStrictMode: false,
async rewrites() {
return [
{
source: '/naver/:path*',
destination: '<https://openapi.naver.com/:path*>',
},
];
},
images: {
remotePatterns: [
{
protocol: 'https',
hostname: 'media1.jjalkey.com',
},
{
protocol: 'https',
hostname: 'localhost',
},
{
protocol: 'https',
hostname: 'example-bucket-seeun.s3.ap-northeast-2.amazonaws.com',
},
],
},
};
docker-compose.yml
version: '3'
services:
nextjs:
image: nextjs:latest
container_name: nextjs
ports:
- '3000:3000'
restart: always
nginx:
image: nginx:latest
container_name: nginx
ports:
- '80:80'
- '443:443'
volumes:
- /etc/ssl:/etc/nginx/ssl:ro
restart: always
nginx.conf
events {
}
http {
upstream nextjs {
server nextjs:3000;
}
server {
# Redirect HTTP requests to HTTPS.
listen 80;
server_name ahwhew.site;
root /srv/public;
return 301 https://$host$request_uri;
}
server {
listen 443 ssl;
server_name ahwhew.site;
root /srv/public;
server_tokens off;
ssl_certificate /etc/nginx/ssl/my_ssl_cert.crt;
ssl_certificate_key /etc/nginx/ssl/my_ssl_key.key;
location / {
try_files $uri $uri/ @nextjs;
}
location @nextjs {
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto https;
proxy_set_header X-Forwarded-Ssl on;
proxy_set_header Host $http_host;
proxy_redirect off;
proxy_pass <http://nextjs>;
proxy_cookie_path / "/; HTTPOnly; Secure";
}
}
}
도커 이미지 빌드 명령어
docker build -t hoonsdev/nginx:latest -f nginx/Dockerfile nginx
docker build -t hoonsdev/nextjs:latest .
도커 컨테이너 한번에 삭제
docker rm -f $(docker ps -qa)