まーぽんって誰がつけたの?

iOS→Scala→インフラなおじさん技術メモ

nginxのテストを気軽にローカル環境でやる方法

nginxの設定は難しい

アプリケーションの開発してたエンジニアにとってnginxの設定をさっと書くのは結構難しいですよね(自分も含めて)。もう試しながらやるしかないと思うので、そんなときに気軽に試せるやり方を紹介。Dockerを使うので、Docker for Macはもちろんインストールしておいてくださいね。

適当にディレクトリ作る

雑にデスクトップにnginxみたいなディレクトリ作る。

mkdir ~/Desktop/nginx

公式のnginxのconfをパクる

# nginx.confをパクる
$ docker run -it nginx:alpine cat /etc/nginx/nginx.conf > ~/Desktop/nginx/nginx.conf
# default.confをパクる
$ docker run -it nginx:alpine cat /etc/nginx/conf.d/default.conf > ~/Desktop/nginx/default.conf

Dockerfileを書く

FROM nginx:alpine

COPY nginx.conf /etc/nginx/nginx.conf
COPY default.conf /etc/nginx/conf.d/default.conf

CMD ["nginx", "-g", "daemon off;"]

Makefileを書く

run:
  docker build -t nginx-test .
  docker run -it -p 8080:80 nginx-test

こういうファイル構成になる

➜  ~ tree Desktop/nginx
Desktop/nginx
├── Dockerfile
├── Makefile
├── default.conf
└── nginx.conf

テスト開始

make run するだけ

➜  nginx pwd
/Users/mpon/Desktop/nginx
➜  nginx make run
docker build -t nginx-test .
Sending build context to Docker daemon  6.656kB
Step 1/4 : FROM nginx:alpine
 ---> bb00c21b4edf
Step 2/4 : COPY nginx.conf /etc/nginx/nginx.conf
 ---> Using cache
 ---> 4c5cd27c66a9
Step 3/4 : COPY default.conf /etc/nginx/conf.d/default.conf
 ---> Using cache
 ---> db9944326ade
Step 4/4 : CMD ["nginx", "-g", "daemon off;"]
 ---> Using cache
 ---> e92d1c2f667f
Successfully built e92d1c2f667f
Successfully tagged nginx-test:latest
docker run -it -p 8080:80 nginx-test

http://localhost:8080 にアクセスして、Welcome to nginx!

あとはお好きに

default.confをいじって、再びmake run すればOK