LoginSignup
1
3

More than 1 year has passed since last update.

はじめに

業務でNext.jsに触れる機会があったのでDockerで開発環境構築をやってみたいと思ったので書いていきます。実際にはMySQLも含みますがサーバーサイド側のため割愛します。

*ローカル開発環境構築の想定のため、セキュリティは本番環境を想定していません。

やりたいこと

docker-composeNginxコンテナをリバースプロキシとしてNode.jsコンテナへリクエストを投げる環境の構築

##環境構築
Docker for Macをインストール済みかつNext.jsでプロジェクト作成済みを想定

docker version

$docker --version
Docker version 20.10.6, build 370c289

ディレクトリ構造

├── docker-compose.yml
├── node
|   ├── Dockerfile 
├── nginx
   ├── default.conf 
  

docker-compose.yml

services:
  nginx:
    image: nginx:1.21-alpine
    container_name: next-nginx
    ports:
      - "80:80"
    depends_on:
      - node
    volumes:
      - ./nginx/default.conf:/etc/nginx/conf.d/default.conf
  node:
    build: ./node
    container_name: node
    volumes:
      - {プロジェクトルーティング}/:/usr/src/app/

Dockerfile

curl使ってAPIとの連携確認できたら便利かなと思い入れています。

FROM node:16-alpine

RUN apk --no-cache add curl

WORKDIR /usr/src/app/

default.conf

server {
    listen 80;
    server_name node.docker.internal;

    root /var/www/public;

    access_log /var/log/nginx/access.log;
    error_log  /var/log/nginx/error.log;

    location / {
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-Host $host;
        proxy_set_header X-Forwarded-Server $host;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_pass 127.0.0.1:3000;
    }
}

/etc/hosts

127.0.0.1 node.docker.internal

docker-compose up

$docker-compose up -d --build // imageダウンロードとかbuildのログがいっぱいでてきます。
$docker-compose ps
    Name                   Command               State                           Ports
--------------------------------------------------------------------------------------------------------------
nginx      /docker-entrypoint.sh ngin ...          Up      0.0.0.0:80->80/tcp,:::80->80/tcp
node       docker-entrypoint.sh npm r ...          Up      3000/tcp, 5000/tcp,

うまく起動できたようなので次はnodeコンテナに入りnpm run devを実行します。

$docker-compose exec node sh
$npm run dev

これでnode.docker.internal:80をたたくとプロジェクトが表示されていると思います。

1
3
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
1
3