This document explain how to intialize and run a Vite.js project inside Docker with docker-compose.
- Docker
Create a Dockerfile from the node image:
# Dockerfile
ARG NODE_VERSION=20
FROM node:${NODE_VERSION}-slim as base
# enable pnpm
ENV PNPM_HOME="/pnpm"
ENV PATH="$PNPM_HOME:$PATH"
RUN corepack enable
# To resolve permissions issues on mounted volume
ARG USER_UID
ARG USER_GID
RUN usermod -aG $USER_UID node && groupmod -g $USER_GID node
USER node
RUN mkdir -p /home/node/app
WORKDIR /home/node/app
Build image
# add -f <path>/Dockerfile if necessary
$ docker build \
--build-arg USER_UID=$(shell id -u $$USER) \
--build-arg USER_GID=$(shell id -g $$USER) \
--build-arg NODE_VERSION=20 \
--target base \
--tag front .
# enter the built container in bash (update mount src if necessary)
$ docker run --user node --mount type=bind,src=./frontend/vue,dst=/home/node/app -it front bash
# create the projects (files will be created on your system because of the docker mount)
node@xxx:~/app$ pnpm create vite
# ...
# enter app folder to create a lock file
node@xxx:~/app$ cd <projet_folder_name>
node@xxx:~/app/<projet_folder_name>$ pnpm install
Add the following to your Dockerfile
# ...
COPY ./<projet_folder_name>/ ./
FROM base AS prod
RUN --mount=type=cache,id=pnpm,target=/pnpm/store pnpm install --prod --frozen-lockfile
FROM base AS dev
RUN --mount=type=cache,id=pnpm,target=/pnpm/store pnpm install --frozen-lockfile
RUN pnpm run build
FROM base
COPY --from=prod-deps /app/node_modules /app/node_modules
COPY --from=build /app/dist /app/distm
Create (or add) service to docker-compose file
# docker-compose.yml
services:
frontend:
container_name: frontend
user: node
build:
context: .
dockerfile: Dockerfile
target: dev
command: pnpm run dev
environment:
- VITE_PORT=${VITE_PORT}
ports:
- ${VITE_PORT}:${VITE_PORT}
volumes:
- ${PWD}/<projet_folder_name>/:/home/node/app
// <projet_folder_name>/vite.config.ts
import { defineConfig, loadEnv } from 'vite'
import vue from '@vitejs/plugin-vue'
// https://vitejs.dev/config/
export default defineConfig(({ mode }) => {
const env = loadEnv(mode, process.cwd());
return {
plugins: [vue()],
server: {
host: true,
port: env.VITE_PORT,
},
};
});
Rebuild to install dependencies
$ docker-compose build \
--no-cache \
--pull \
--build-arg USER_UID=$(shell id -u $$USER) \
--build-arg USER_GID=$(shell id -g $$USER) \
--build-arg NODE_VERSION=20
# update VITE_PORT if required
$ VITE_PORT=5000 docker compose up