Vue with Docker; initialize, develop and build
Let’s initialize a Vue project from a docker container; build the Vue project with a multi-stage Dockerfile; and finish with how to develop in debug mode with docker-compose!
All that is required is that you have docker and docker-compose installed locally.
Initialize the project
Run the following command while replacing myproject
with your project name:
mkdir myproject && cd "$_" && docker run --rm -v "${PWD}:/$(basename `pwd`)" -w "/$(basename `pwd`)" -it node:11.1-alpine sh -c "yarn global add @vue/cli && vue create ."
It creates the directory and runs a node container with the Vue/cli mounted to this directory. When installing choose yarn.
Dockerfile
The Dockerfile
is identical to the given example in the documentation. Only the build-stage is split up into an install-stage and a build-stage, since we don’t need to build when we are developing!
# develop stage
FROM node:11.1-alpine as develop-stage
WORKDIR /app
COPY package*.json ./
RUN yarn install
COPY . .# build stage
FROM develop-stage as build-stage
RUN yarn build# production stage
FROM nginx:1.15.7-alpine as production-stage
COPY --from=build-stage /app/dist /usr/share/nginx/html
EXPOSE 80
CMD ["nginx", "-g", "daemon off;"]
You can build this container with:
docker build -t dockerize-vue .
and… run the container:
docker run -it -p 8000:80 --rm dockerize-vue
We should now be able to access the application on localhost:8000.
Develop with Docker-compose.yml
While developing, you don’t want to rebuild the container all the time in order to see the results in your browser. To keep the reload functionality of the development mode we share the code base with the container with docker-compose. In fact, the docker-compose.yml
file is fairly simple:
# for local development
version: '3.7'
services:
frontend:
build:
context: .
target: 'develop-stage'
ports:
- '8080:8080'
volumes:
- '.:/app'
command: /bin/sh -c "yarn serve"
We only build the develop-stage
since we need the source code, node, yarn, the installed vue-cli, and so on. Build the image and run the application in development mode with docker-compose:
docker-compose up --build
You should now be able to access the application on localhost:8080. When making changes to the code, the application will still reload in the browser!
In case you want to add another node package, just run the following command:
docker-compose exec frontend yarn add <package-name>
So that’s it, have fun with Docker and Vue!