Docker deploys the Vue project

1. Write at the front:

As a lightweight virtualization technology, Docker has the advantages of continuous integration, version control, portability, isolation and security. This paper uses Docker to deploy a front-end application of VUE, and as detailed as possible to introduce the implementation ideas and specific steps, for the convenience of students with similar needs for reference.

Docker container is an open source application engine, allows developers to pack their applications and rely on the package to a portable container, the container contains the application code, running environment, rely on libraries, the configuration file, such as the necessary resources, can be achieved by container convenient fast and automated deployment with platform decoupling way, The applications in the container will run in the same environment regardless of the environment in which you deploy. (Please visit docker website for more details)

Docker, @vue/ CLI is already installed by default

Related version:

  • Docker version 18.09.2, build 6247962

  • Vue cli – version 3.3.0

  • MacOS Mojave verizon 10.14.1

The operating environment is macOS. If there is a difference between the operating system and the reader’s operating system, please adjust it by yourself

Related images:

  • nginx:latest
  • node:latest

2. Concrete implementation:

  1. Use the Vue CLI to create a vue project, modify the created project, write a front-end interface request on the page, build a version of online resources, build a front-end engineering image based on the Nginx Docker image, and then based on the front-end engineering image, Start a container, vuenginxContainer.
  2. Start nodeWebServer, a container based on node images that provides a back-end interface.
  3. Modify the nginx configuration of VuenginxContainer to forward interface requests from front-end pages to NodeWebServer.
  4. A little refinement and improvement.

3 Create a VUE application

3.1 VUE CLI Create a VUE project

yarn serve / npm run serve
Copy the code

http://localhost:8081

3.2 rewrite

Rewrite the page slightly, pass in the HelloWorld component in app. vue and change the MSG to Hello Docker; Adds an interface request to the Created lifecycle

import axios from 'axios'; ... axios.get('/api/json', {
  params: {}
}).then(
  res= > {
    console.log(res);
  }
).catch(
  error= > {
      console.log(error); })...Copy the code

You will see an error message on the page console:

3.3 Build the VUE project

Run the command

yarn build / npm run build
Copy the code

dist

If you upload the dist directory to the server in its entirety, you can deploy it as a static resource site and have direct access to the project.

Let’s build one of these static resource sites.

4 Create a VUE application image

Nginx is a high performance HTTP and reverse proxy server. Here we use nginx image as the base to build our VUE application image.

4.1 Obtaining an Nginx Image

docker pull nginx
Copy the code
  • dockerImage A special file system. Docker image is a special file system, in addition to providing programs, libraries, resources, configuration files required by the container runtime, but also contains some configuration parameters prepared for the runtime (such as anonymous volumes, environment variables, users, etc.). The image does not contain any dynamic data and its contents are not changed after the build.
  • The operations related to docker images are as follows: Search for imagesdocker search [REPOSITORY[:TAG]]And pull the mirror imagedocker pull [REPOSITORY[:TAG]], view the mirror listdocker image ls, Delete a mirror:docker image rm [REPOSITORY[:TAG]] / docker rmi [REPOSITORY[:TAG]]And so on.
  • Docker image names consist of REPOSITORY and TAG[REPOSITORY[:TAG]]TAG defaults to Latest

4.2 Creating the Nginx Config Configuration File

Create an nginx folder in the root directory of your project and create a new file, default.conf

server {
    listen       80;
    server_name  localhost;

    #charset koi8-r;
    access_log  /var/log/nginx/host.access.log  main;
    error_log  /var/log/nginx/error.log  error;

    location / {
        root   /usr/share/nginx/html;
        index  index.html index.htm;
    }

    #error_page 404 /404.html;

    # redirect server error pages to the static page /50x.html
    #
    error_page   500 502 503 504  /50x.html;
    location = /50x.html {
        root/usr/share/nginx/html; }}Copy the code

Pointing to the homepage of the configuration file defines as/usr/share/nginx/HTML/index. The HTML, so we can for a while to build up the index. HTML documents and related static resource in/usr/share/nginx/HTML directory.

4.3 Creating a Dockerfile File

FROM nginx
COPY dist/ /usr/share/nginx/html/
COPY nginx/default.conf /etc/nginx/conf.d/default.conf
Copy the code
  • Custom build images are built based on Dockerfile.
  • FROM nginxThis image is built based on nginx:latest image.
  • COPY dist/ /usr/share/nginx/html/Copy all files from the dist folder in the root directory of the project to /usr/share/nginx/html/.
  • COPY nginx/default.conf /etc/nginx/conf.d/default.confCommand will mean nginx directory. The default conf copied to the/etc/nginx/conf. D/default. Conf, with local default. Conf configuration to replace nginx default configurations in the mirror.

4.4 Build a VUE application Image based on the Dockerfile

Run the command (be careful not to miss the last “. )

docker build -t vuenginxcontainer .
Copy the code

-t is to name the image. It is to build the image based on the Dockerfile of the current directory

docker image ls | grep vuenginxcontainer
Copy the code

vue
docker

4.5 Starting the Vue APP Container

Docker Container Container: the entity in which the image is run. The relationship between an Image and a Container is similar to that between a class and an instance in object-oriented programming. An Image is a static definition and a Container is an entity of the Image runtime. Containers can be created, started, stopped, deleted, paused, and so on.

Start the container based on the vuenginxContainer image, run the following command:

docker run \
-p 3000:80 \
-d --name vueApp \
vuenginxcontainer
Copy the code
  • docker runStart a container based on the image
  • -p 3000:80Port mapping, which maps port 3000 of the host to port 80 of the container
  • -dBackground mode running
  • --nameContainer name view docker process
docker ps
Copy the code

http://localhost:3000

docker

5 Interface Service

Deploy a node container to provide interface services

5.1 express service

Write a service using Node Web framework Express to register a route server.js that returns json data format:

'use strict';

const express = require('express');

const PORT = 8080;
const HOST = '0.0.0.0';

const app = express();
app.get('/', (req, res) => {
    res.send('Hello world\n');
});

app.get('/json', (req, res) => {
    res.json({
        code: 0.data :'This is message from node container'})}); app.listen(PORT, HOST);console.log(`Running on http://${HOST}:${PORT}`);
Copy the code

Running the Express application requires a Node environment, and we build a new image based on the Node image

5.2 getnodeThe mirror

docker pull node
Copy the code

5.3 Writing a Dockerfile willexpressapplicationdocker

FROM node

WORKDIR /usr/src/app

COPY package*.json ./

RUN npm install

COPY.
EXPOSE 8080
CMD [ "npm"."start" ]
Copy the code

Node_modules dependencies are installed directly through RUN NPM install when building the image, and a.dockerignore file is created in the project to ignore some files that are skipped directly:

node_modules
npm-debug.log
Copy the code

5.4 Building a NodeWebServer Image

Run the build command:

  docker build -t nodewebserver .
Copy the code

5.5 Starting the Nodeserver Container

Start a container named Nodeserver based on the nodeWebServer image you just built to provide interface service port 8080 and map the host’s port 5000

docker run \
-p 5000:8080 \
-d --name nodeserver \
nodewebserver
Copy the code

View the current Docker process

docker ps
Copy the code

http://localhost:5000/json

6. Cross-domain forwarding

You want to forward requests from the vueApp container to the Nodeserver container. First of all, we need to know the IP address and port of nodeserver container. At present, it is known that the nodeserver container internal service listens on port 8080, and we also need to know the IP address.

6.1 Viewing the IP Address of the Nodeserver Container

There are several ways to view the internal IP of a container. Here are two ways:

  • Look inside the container
docker exect -it 02277acc3efc bash
Copy the code
cat /etc/hosts
Copy the code

  • Docker inspect [containerId]
docker inspect 02277acc3efc
Copy the code

Find the Networks related configuration information:

6.2 Modifying the Nginx Configuration

  • Nginx configurelocation to point to the node service default.conf (Nginx).
  • Add a rewrite rule to redirect/API /{path} to the target service’s /{path} interface. Add the following to the previous nginx/default.conf file:
location /api/ {
  rewrite  /api/(.*)  /The $1  break;
  proxy_pass http://172.17.0.2:8080;
}
Copy the code

After making the changes, I realized that the vueApp container is based on the image of vuenginxContainer, and the nginx configuration default.conf was built directly into the image at the beginning. So if you want to change default.conf, you have to build a new image and run the new container based on the new image.

7. To improve

Can you restart the container every time you change the configuration file to make the new configuration take effect? Yes.

Instead of copying the Nginx configuration to the image, mount it directly to the host and restart the container after each configuration change.

7.1 Modifying Dockerfile Files

Modify the Dockerfile under vueclidemo project

FROM nginx
COPYdist/ /usr/share/nginx/html/COPY nginx/default.conf /etc/nginx/conf.d/default.conf
Copy the code

Will COPY nginx/default conf/etc/nginx/conf. D/default. Conf command delete, nginx configuration is through the mount command to mount on the host machine. COPY dist/ /usr/share/nginx/ HTML /, if you need to build a new image and start a new container every time the contents of the dist/ build are changed, you can remove this command and start the container by mounting it.

7.2 Restarting the VUE Application Container

To start the container vuenginxnew directly from the nginx image, run the following command:

docker run \
-p 3000:80 \
-d --name vuenginxnew \
--mount type=bind.source=$HOME/SelfWork/docker/vueclidemo/nginx,target=/etc/nginx/conf.d \
--mount type=bind.source=$HOME/SelfWork/docker/vueclidemo/dist,target=/usr/share/nginx/html \
nginx
Copy the code
  • --mount type=bind,source={sourceDir},target={targetDir}Mount the host’s sourceDir to the container’s targetDir directory.
  • The command running here is long, and if it is troublesome to re-type each time, we can save the entire command to oneshellfilevueapp.shThen execute the command directlysh vueapp.sh.

This way, every time you change your Nginx configuration or rebuild your Vue application, you just need to restart the container to take effect immediately. At this time we will visit http://localhost:3000/api/json to see interface can return to normal, the forward effect.

7.3 Configuring load Balancing

Back-end services are usually two-node or multi-node to ensure service stability. We can start another back-end service container and modify the configuration of Nginx to optimize resource utilization, maximize throughput, reduce latency, and ensure fault-tolerant configuration.

Start a new container based on a similar operation in Section 4.5 and check the IP address of the new container based on a similar operation in Section 5.1.

(upstreams added to location/API/proxy_pass) :

Upstream Backend {server 172.17.0.2:8080; Server 172.17.0.3:8080; }... location /api/ { rewrite /api/(.*) /$1 break; proxy_pass backend; }Copy the code

8. Write in the back

Students who are not used to the command line can choose Kitematic to manage the docker container state, data directory and network. All operations on the capacity can be visualized, so I don’t want to introduce too much here, but interested students can experience it by themselves.

9 summary

Docker provides a very powerful automated deployment mode and flexibility, decoupling multiple applications, providing agility, controllability and portability in development. This paper takes vUE project as an example to realize a complete step of deploying docker in a separate project, hoping to bring some help to students who want to embrace Docker.

10 Tail by hand

The front end team of Kuaigou Taxi focuses on sharing front-end technology and regularly pushes high-quality articles, which are welcome to be praised.

The resources

The docker’s official website

Nginx website

Docker goes from starter to practice

Kitematic user guide

What the front end wants to know about Nginx

Nginx location matching