React開発環境をDockerでサクッと構築


Dockerfile

FROM ubuntu:latest

RUN apt-get update && apt-get install -y curl
RUN curl -sL https://deb.nodesource.com/setup_12.x | bash
RUN apt-get install -y nodejs
RUN curl -sS https://dl.yarnpkg.com/debian/pubkey.gpg | apt-key add && echo "deb https://dl.yarnpkg.com/debian/ stable main" | tee /etc/apt/sources.list.d/yarn.list && apt update && apt install -y yarn

ENTRYPOINT [ "/bin/bash"]

WORKDIR /react-sample

上のDockerfileがあるディレクトリで以下のコマンドを実行します。

docker build . -t react/ubuntu:latest

これでreact開発に必要なyarnとnode.jsをインストールしたイメージを作成できました。
image名はreact/ubuntu:latestと付けています。

reactアプリを作成

create-react-appを使ってサンプルプロジェクトを作成してみます。
create-react-appをインストールして、react-sampleという名前のプロジェクトを作成するために以下のコマンドを実行します。

yarn global add create-react-app
create-react-app react-sample

dockerコンテナ

先ほど作成したdockerイメージとサンプルプロジェクトを使って、dockerコンテナを作成します。

docker run -p 3000:3000 -v /[ホストのパス]/react-sample:/react-sample -it react/ubuntu:latest

localhost:3000でプロジェクトにアクセスするために -pでポートフォワーディング、-vでプロジェクトをコンテナ内にマウントしています。

あとは以下のコマンドを実行すればアプリを起動できます。

yarn 
yarn start

参考になれば幸いです!