フリーランス 技術調査ブログ

フリーランス/エンジニア Ruby Python Nodejs Vuejs React Dockerなどの調査技術調査の備忘録

dockerでnginx+nuxtjsの環境を構築する

はじめに

  • strapiの環境を構築したので、nuxtjs環境を構築してstrapiのAPIを実行する環境を構築する

px-wing.hatenablog.com

docker関連の設定

  • 下記の設定はdocker-compose up -dで全てが起動される環境ではありません。nginxは自動起動します。

docker-compose.yaml

version: '3'
services:
  nginx:
    build: ./containers/nginx/
    container_name: nginx
    ports:
      - '80:80'
    privileged: true
    volumes:
      - ./frontend:/srv/frontend/app
    command: /sbin/init
    tty: true

Dockerfile

FROM amazonlinux:latest

RUN yum update -y

## nginx
RUN yum install -y amazon-linux-extras
RUN amazon-linux-extras install nginx1
RUN systemctl enable nginx

COPY ./nginx.conf /etc/nginx/

## nodejs
RUN curl -sL https://rpm.nodesource.com/setup_14.x | bash -
RUN yum install nodejs -y
RUN yum -y install wget
RUN wget https://dl.yarnpkg.com/rpm/yarn.repo -O /etc/yum.repos.d/yarn.repo
RUN yum -y install yarn

WORKDIR /srv/frontend/app

nginx.confファイル

  • nuxtjsをlocalhost:3000で起動した場合、nginxを介して80ポートでアクセスできるようにするための設定
user nginx;
worker_processes auto;
error_log /var/log/nginx/error.log;
pid /run/nginx.pid;

# Load dynamic modules. See /usr/share/doc/nginx/README.dynamic.
include /usr/share/nginx/modules/*.conf;

events {
    worker_connections 1024;
}

http {
    log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                      '$status $body_bytes_sent "$http_referer" '
                      '"$http_user_agent" "$http_x_forwarded_for"';

    access_log  /var/log/nginx/access.log  main;

    sendfile            on;
    tcp_nopush          on;
    tcp_nodelay         on;
    keepalive_timeout   65;
    types_hash_max_size 4096;

    include             /etc/nginx/mime.types;
    default_type        application/octet-stream;

    # Load modular configuration files from the /etc/nginx/conf.d directory.
    # See http://nginx.org/en/docs/ngx_core_module.html#include
    # for more information.
    include /etc/nginx/conf.d/*.conf;

    server {
        listen       80;
        listen       [::]:80;
        server_name  _;
        root         /srv/frontend/app/static;

        # Load configuration files for the default server block.
        include /etc/nginx/default.d/*.conf;

        location / {
          proxy_pass http://localhost:3000;
        }

        error_page 404 /404.html;
            location = /40x.html {
        }

        error_page 500 502 503 504 /50x.html;
            location = /50x.html {
        }
    }

}
  • 上記の設定を元にbuildを実行する
$ docker-compose build

nuxtjsのサーバーを起動する

  • dockerの起動
$ docker-compose up -d
  • dockerにログイン後、プロジェクトの作成
$ docker exec -it nginx bash
$ yarn create nuxt-app <project-name>
(※ プロジェクト作成完了後、<project-name>フォルダ内にある全てのファイルを一階層上に移動して、空になった<project-name>フォルダを削除してください。vscodeで作業すると楽です。)
  • nuxtjsを起動する
$ yarn dev
  • pages/index.vueファイルの内容を下記のHelloWorldを参考に書き換えてhttp://localhostにアクセスすると下記が表示される f:id:PX-WING:20201208125720p:plain

ja.nuxtjs.org