2
1

Next.js + NginxサーバーをDockerで構築した話

Last updated at Posted at 2023-11-10

はじめに

数ヶ月前にNext.jsの本番環境をDockerで構築したのですが、Nginxはホストマシンで立ててしまっていたため、Nginxの設定を都度サーバー上で書かないといけないという問題がありました。

そこで今回はNext.jsのサーバーに加えてNginxサーバーもDockerで構築することにしました。

ディレクトリ構成

- root
  - nginx # new!
    - Dockerfile
    - nginx.conf
  - node_modules
  - public
  - src
  ...
  - docker-compose.yml
  - Dockerfile
  - package.json
  - yarn.lock

Nginx関連の設定

nginx/nginx.conf
server {
  listen 80;
  server_name www.example.com;

  location / {
    proxy_pass http://app:4400; # appはNextサーバーの名前
    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;
  }
}

Dockerの設定

nginx/Dockerfile.
FROM nginx:alpine

RUN rm -f /etc/nginx/conf.d/*

ADD nginx.conf /etc/nginx/conf.d/portfolio.conf

CMD /usr/sbin/nginx -g 'daemon off;'
docker-compose.yml
version: '3'

services:
  app:
    container_name: next-app
    image: next-app
    build:
      context: .
      dockerfile: Dockerfile
    restart: always

  nginx:
    container_name: next-app-nginx
    build:
      context: ./nginx
      dockerfile: Dockerfile
    ports:
      - {好きなポート番号}:80
    depends_on:
      - app

おわりに

これで晴れてホストマシンにnginxの設定を記述しなくても済むようになりました。次回はRailsサーバーで使っているNginxサーバーをDockerに移行していきたいと思います。

2
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
1