LoginSignup
2
2

More than 3 years have passed since last update.

React.jsをDockerで動かした時のメモ

Last updated at Posted at 2020-06-30

環境

$ cat /etc/linuxmint/info 
RELEASE=19.3
CODENAME=tricia
EDITION="Cinnamon"
DESCRIPTION="Linux Mint 19.3 Tricia"
DESKTOP=Gnome
TOOLKIT=GTK
NEW_FEATURES_URL=https://www.linuxmint.com/rel_tricia_cinnamon_whatsnew.php
RELEASE_NOTES_URL=https://www.linuxmint.com/rel_tricia_cinnamon.php
USER_GUIDE_URL=https://www.linuxmint.com/documentation.php
GRUB_TITLE=Linux Mint 19.3 Cinnamon

Dockerのインストール

$ apt update
$ apt install docker-ce docker-ce-cli docker-compose

node.jsとcreate-react-appのインストール

$ apt install nodejs
$ npm install create-react-app yarn

サンプルReact.jsアプリを作る

$ create-react-app docker-test
$ cd docker-test

とりあえず普通に起動してみる。

yarn start

ブラウザで http://localhost:3000 にアクセスしReact.jsが動作していることを確認。
確認できたらCtrl-Cで落とす。

Dockerfileとdocker-compose.ymlを作成

作成したReactアプリのルートディレクトリに以下のような内容で Dockerfiledocker-compose.yml を作る。

Dockerfile
FROM node:14.4.0-buster-slim
WORKDIR /usr/src/app
RUN npm install --save prop-types
RUN npm install -g create-react-app
docker-compose
version: '3'
services:
  node:
    build:
      context: .
    tty: true
    environment:
      - NODE_ENV=production
    volumes:
      - ./:/usr/src/app
    command: sh -c "yarn start"
    ports:
      - "3000:3000"

上記のような内容だと、作成したReactアプリのルートディレクトリがDocker環境内では /usr/src/app にマウントされるため、 WORKDIRを /usr/src/app に指定してあれば、実行するスクリプトは sh -c "yarn start" だけとなるため、これを command で指定している。

docker-hub nodeを見に行くと、alpine buster stretch などの名前がバージョンについています。なんのことかと思ったらLinuxディストリビューションですね。

slim とついているものは、Debianディストリビューションでエクストラパッケージが含まれないものです。いずれにしても今回はDockerでnodeが動けばいいので node:14.4.0-buster-slim を選択しました。
ちなみにDebianの現在のバージョンは buster(10.0) であり、それ以前は以下のようになります。

Debian 10 (buster) — 現在の安定版リリース
Debian 9 (stretch) — 過去の安定版リリース
Debian 8 (jessie) — 過去の安定版リリース
Debian 7 (wheezy) — 過去の安定版リリース

alpine linuxはパワーユーザー向けの軽量Linuxのようです。軽量だけにイメージが小さく抑えられるかもしれませんが、私はDebianやUbuntuしか使ったこと無いので alpine の使用はやめておきました。

Dockerイメージをビルド

$ docker-compose build

DockerでReact.jsアプリを実行する

起動

$ docker-compose up

ブラウザで http://localhost:3000 にアクセスしReact.jsが動作していることを確認。
Ctrl-C で停止。

バックグラウンドで起動

$ docker-compose up -d

停止

$ docker-compose down

イメージ情報を確認

$ docker images | grep dockertest
dockertest_node     latest               daf22d9465c7        26 minutes ago      194MB

おまけ

すべてのDockerイメージを停止

$ docker stop $(docker ps -q)
2
2
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
2