githubにソースコード置いてます: nginx-simple-example
今回は,nginxで静的コンテンツの表示というのをやってみたいと思う.自分の環境を汚したくないので,dockerを使う.nginxのdockerイメージはすでにあるので,これをベースに作っていく.ディレクトリ構成は以下.
nginx-simple-example/
Dockerfile
src/
index.html
css/
style.css
js/
hello.js
nginx/
nginx-simple-example.conf
src/
の中身が静的コンテンツで,例えばwebpackの出力なんかを想定している(多分こんな感じだった気がする…).nginx/
配下にnginxの設定ファイルをおく.
nginxの設定ファイルは以下のようにする.
nginx-simple-example.conf:
server {
listen 80;
server_name localhost;
location / {
root /usr/local/nginx-simple-example;
index index.html index.htm;
}
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root /usr/share/nginx/html;
}
}
ほとんどデフォルトのままだが,rootを変えている.nginxというかwebserverが具体的にどのような役割を担っているのか,あんまり知らなかったので,調べてみた.僕の理解では,/
にアクセスすると,/usr/local/nginx-simple-example
をみて,その中のindex.html
が表示されるという具合なんだと思う.となると,/css
にアクセスすれば,/usr/local/nginx-simple-example/css
にアクセスしていることになる.この仕組みを想定すれば,index.html
で,cssやjsの読み込みは以下のようになるだろう.
index.html:
<html>
<head>
<link href="/css/style.css" rel="stylesheet" type="text/css">
<script type="text/javascript" src="/js/hello.js"></script>
</head>
<body>
<h1>Hello World!</h1>
</body>
</html>
/
がhref
やsrc
の先頭についていることに注意.
次にDockerfileは以下のようにした.
Dockerfile:
FROM nginx
COPY ./src /usr/local/nginx-simple-example
COPY ./nginx/nginx-simple-example.conf /etc/nginx/conf.d/default.conf
どうやら,default.conf
というのが最初からあるようで,今回はこれを上書きしているが,どうにか共存させることもできそう.これは後日調べようと思う.
最後に,style.css
とhello.js
の中身も載せておく.
style.css:
h1 {
color: red;
}
hello.js:
console.log("Hello World!")
これでビルドする.
docker build --tag nginx-simple-example .
で,runする.
docker run --rm -p 8080:80 --name webserver nginx-simple-example
localhost:8080
にアクセスすると,赤字のHelloWorld!が表示される.それとconsoleにHelloWorld!が出力されていると思う.
かなりシンプルにできた.ソースはgithubに置いてます.
nginx-simple-example
Written with StackEdit.
0 件のコメント:
コメントを投稿