はじめに
DockerでViteとVue3の開発環境を立ち上げる作業を行った。映し出すまでに少し手間どってしまったので、理解を深めるためにもメモを残す。
ゴール
オンプレサーバー内の仮想OSでDockerを導入していてdocker compose v2なども導入済みです。
今回のゴールはAmazonLinux2023のイメージを利用してVite+Vue3の開発環境をhttp://xxx.xxx.xxx.xxx:5173
でアクセスできる状態にすることです。
参考:
https://zenn.dev/iloveomelette/scraps/da45d505ffaefc
https://qiita.com/generonishimura/items/88742085294bd0b234a6
作業手順
- 開発用ディレクトリを作成
-
Dockerfile
とcompose.yml
を作成
FROM amazonlinux:2023
# dnfのアップデート
RUN dnf update -y
# Node.jsのインストール
RUN curl -sL https://rpm.nodesource.com/setup_20.x | bash - && \
dnf install -y nodejs
# Viteのインストール
RUN npm install -g vite
# コンテナ内の作業ディレクトリを作成
WORKDIR /app
# ポート番号5173でコンテナを公開
EXPOSE 5173
compose.yml
services:
frontend: # サービス名
build: # Dockerfileの設定
context: . # Dockerfileを置いているディレクトリ
dockerfile: Dockerfile # Dockerfileのファイル名
working_dir: /app # 作業ディレクトリを指定
volumes:
- ./:/app:cached
tty: true # コンテナを正常終了するのを防ぐ
ports:
- '5173:5173' # 公開用のポート指定。ホスト側:コンテナ側
command: npm run dev # viteの実行コマンド
volumes: # 名前付きボリュームの設定
node_modules:
3.ホストマシン(仮想OS)でビルド
docker compose build
4.Dockerコンテナ内でViteを利用してVueアプリを作成(Vueを指定し、プロジェクト名は今回は「vue-vite-sample」とした)
docker-compose run frontend npm run vite
5.Dockerfileとcompose.ymlに追記する
FROM amazonlinux:2023
# dnfのアップデート
RUN dnf update -y
# Node.jsのインストール
RUN curl -sL https://rpm.nodesource.com/setup_20.x | bash - && \
dnf install -y nodejs
# Viteのインストール
RUN npm install -g vite
# コンテナ内の作業ディレクトリを作成
WORKDIR /app
# 追記
# プロジェクトのコピー
COPY vue-vite-sample/ ./
# ポート番号5173でコンテナを公開
EXPOSE 5173
compose.yml
services:
frontend:
build:
context: .
dockerfile: Dockerfile
working_dir: /app
volumes:
- ./vue-vite-sample:/app:cached
- node_modules:/app/node_modules
tty: true
ports:
- '5173:5173'
command: npm run dev
volumes:
node_modules:
6.vite.config.tsを書き換え(ホストではなく外部公開するため)
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
// https://vitejs.dev/config/
export default defineConfig({
plugins: [vue()],
server: {
// 外部公開
host: '0.0.0.0',
// 立ち上げる際のポートを変更できます。
port: 5173
}
})
7.再度ビルドする
docker compose build --no-cache
8.コンテナの立ち上げ
docker compose up
9.IPとポートを指定してアクセス
http://xxx.xxx.xxx.xxx:5173/