0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

DockerでNext+TypeScriptの開発環境を作る方法

Posted at

はじめに

DockerでNext+TypeScriptの開発環境を作る方法はネットにあったのですが、自分の環境下ではうまくいかないこともあったのでメモとして共有させていただきます。
当方は「WSL2+Ubuntu-20.04」で開発を行っています。

フォルダ構成

フォルダ構成は以下のとおりです。
project
├frontend
│ └sample-app #空のフォルダ
│ └Dockerfile
└docker-compose.yml

具体的な手順

まず、Dockerfileを以下のとおり作成します。

FROM node:18.16.0-alpine3.18
 
# ENV PROJECT /frontend
 
# WORKDIR ${PROJECT}

# RUN apk update && \
#     npm install -g create-react-app && \
#     npm install -g create-next-app

# COPY .${PROJECT} ${PROJECT}

# RUN npm cache verify
# RUN npm install


# CMD ["npm", "run", "dev"]

次に、docker-compose.ymlを以下のとおり作成します。

version: "3.3"

frontend:
    build:
      context: .
      dockerfile: "./frontend/Dockerfile.next"
    volumes:
      - ./frontend:/frontend
    ports:
      - "3000:3000"

以上のファイルを作成したらprojectディレクトリで以下のコマンドを実行しイメージを作成します。

docker compose build

イメージが作成出来たら、以下のコマンドを実行しコンテナに入りsample-appフォルダに移動します。

docker compose run --rm frontend sh
cd sample-app

そして、以下のコマンドを実行します。「sample-app」は任意の名前に変更可能です。

create-next-app sample-app --typescript

そうすると、以下のような質問が出てくるので答えていきます。
私は上から、「Yes,Yes,Yes,Yes,No」と答えました。

✔ Would you like to use ESLint? … No / Yes
✔ Would you like to use Tailwind CSS? … No / Yes
✔ Would you like to use src/ directory? … No / Yes
✔ Would you like to use App Router? (recommended) … No / Yes
✔ Would you like to customize the default import alias? … No / Yes

質問に答えると諸々の処理が行われます。Nextのプロジェクトの作成が完了したら以下のコマンドを実行してコンテナから抜けます。

exit

後は、作成されたNextプロジェクトのファイルフォルダ一式をfrontend直下に移動させます。そして、sample-appフォルダを削除します。最終的に以下のような構成になるはずです。
project
├frontend
│ └app
│ └node_modules
・ ・  
・ ・  
・ ・  
│ └Dockerfile
└docker-compose.yml

次に、Dockerfileのコメントアウトを解除します。

FROM node:18.16.0-alpine3.18

# コメントアウトを解除

ENV PROJECT /frontend
 
WORKDIR ${PROJECT}

RUN apk update && \
    npm install -g create-react-app && \
    npm install -g create-next-app

COPY .${PROJECT} ${PROJECT}

RUN npm cache verify
RUN npm install


CMD ["npm", "run", "dev"]

解除したらprojectディレクトリで以下のコマンドを実行しイメージを再作成します。

docker compose build

その後、以下のコマンドを実行し、http://localhost:3000にアクセスしNextのアプリの画面が表示されれば開発環境の構築は完了です。

docker compose up

まとめ

以上、とりあえず動作するDockerを用いたNext+TypeScriptの開発環境の作り方を説明しました。

0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?