Code God Road Blog Deployment Tutorial [full version] | Linux-based Docker deployment tutorial | Very detailed

illustrate

  • Foreword: Recently, I did a SpringBoot training project with the road of Biz Station Code God. I encountered many difficulties and problems in the first operation, especially in the deployment part, I took a lot of detours. Here I write down my own deployment process for everyone. For reference, you are also welcome to put forward your valuable comments.
  • Beep station code god video link: https://www.bilibili.com/video/BV1Gb4y1d7zb?p=36
  • My website: www.zhangshidi.space (may be updated to other content after a while~)
  • It's not easy to create, I hope you all pass by and give it a thumbs up.
  • Some instructions may be wrong, you can do it manually (for example, in the tutorial I read, mkdir is used to create files such as blog.conf, but there is a problem with the file format, and it will always have a suffix such as blog.conf.swp What, then I manually create a new file in the file directory on the left, and later found that the new file can be successfully created by touch; mkdir is better to create a folder)

Pre-knowledge

  • The following knowledge points hope that you will first search and read, and have a general understanding.
    • What is Linux and some basic instructions to master Linux.
    • What is docker, the principle of docker deployment
    • what is nginx
  • what are we going to do
    • Package the Vue front-end project to the cloud server
    • Package the springboot backend project (main web page, hereinafter referred to as app) (backend management system, hereinafter referred to as admin) to the cloud server
    • Use docker to deploy mysql, redis, ngix, app, admin. Then use docker-compose to perform a service arrangement, so that the projects are started in sequence.

File Directory

  • If you completely follow my ideas, you can check my file directory to check if the file is not correct.insert image description here

1 Environment preparation: server purchase (and domain name)

  • Basic environment (cloud server and domain name) – do it in advance !
  • My cloud configuration: Alibaba Cloud 1 core 2 GiB server + Tencent Cloud domain name.
  • The cloud server is equivalent to our second computer, but it is in the cloud. Because of its relationship in the cloud, we can harass him at will. If there is a more troublesome problem, we can directly reinstall the system without causing any damage to our computer itself. influence.
    • First of all, we need a cloud server, then we need to buy a cloud server, if we need a domain name, we need to buy a domain name, and complete the binding (resolution) between the domain name and the cloud server IP address. It is also possible to temporarily use an IP address without a domain name.
    • Reasons for doing this in advance: Because the domain name needs to be filed , it is said that the filing time may be as long as one week. My (ordinary domain name purchased in Tencent Cloud - 10 years 180) is fine, and the filing is completed in one day. The cloud server was purchased at the Alibaba Cloud event on Double Eleven in 2021 last year. As for which one is good and which one is bad, I think it should be about the same. I picked the cheap ones and bought them.
    • After purchasing the server, you need to install the linux system on the server. I chose the centoS 7.8 version.
    • Then for the use of this cloud server, we can directly enter instructions on the cloud server | or use third-party tools, such as Xshell. (I use xshell, which has fewer bugs and is more fluent)
    • Please search for the above steps by yourself.
    • After completing these steps, a very important thing is to open ports . In the case of Alibaba Cloud, it is in the configuration of security group rules, such as port 8888, redis port, database port, etc. we use, otherwise it may not be accessible.
      insert image description here

2 Docker installation

  • In my understanding of docker, docker can be understood as a container, which is equivalent to a more miniature linux system, in which we can deploy various environments and configurations.
    • For more specific knowledge of docker, we can refer to this article: https://blog.csdn.net/weixin_46628200/article/details/106668209

start installation

  • First enter our cloud server management panel - remote connection, you can see such an empty page, and then we enter various commands here. Cloud server operation interface- We noticed that there are two symbols in the upper left corner, one is [New Command Window]; the other is [Visual View File], which is almost the same as we usually view files. Sometimes you can move directly in the file if you are too lazy to use the copy command.Common operations are fast

docker install

  • Type the following series of commands step by step into your command window
# 1、yum 包更新到最新 
yum update
# 2、安装需要的软件包, yum-util 提供yum-config-manager功能,另外两个是devicemapper驱动依赖的 
yum install -y yum-utils device-mapper-persistent-data lvm2
# 3、 设置yum源
yum-config-manager --add-repo https://download.docker.com/linux/centos/docker-ce.repo
# 4、 安装docker,出现输入的界面都按 y 
yum install -y docker-ce
# 5、 查看docker版本,验证是否验证成功
docker -v
#启动docker
/bin/systemctl start docker.service

Docker installation and startup
Pull the docker image

  • The docker image can be understood as an ordinary image, and the docker image is used to create our docker container.
  • Still enter the following command in the command window
docker pull nginx
docker pull redis:5.0.3
docker pull java:8
docker pull mysql:5.7

3 docker configure mysql

  • Next, I will collectively refer to cloud servers as hosts.

Idea: Build a docker to configure MySQL; and arrange the MySQL data files in the host, which is a little more troublesome, but the security is improved

Before configuring mysql, I hope you will install MySQL on your own host first , and follow the nanny-level mysql installation tutorial on linux .
The reason for this is because I want to store the mysql data on the host machine, and only configure a mysql environment in docker. If the database files are stored on the docker, once the container is deleted (through the rm command), all the data files will disappear , very unsafe.

  • Create a MySQL directory on the host (create a folder command mkdir, cd is a switch directory command)
mkdir -p /mnt/docker/mysql
cd /mnt/docker/mysql
  • Go ahead and run the following commands in the command window
    • Which runhas the role of [create and run] the mysql container
    • -p is to establish the mapping between the host 3307 port and the container 3306 port
    • -v is to generate a mount directory. Mounting can be understood as sharing/synchronizing a file directory. The directory before the colon is the host directory, and after the colon is the MySQL data directory in the docker. Even if the docker is deleted, the data can still be retained to the host. in the host's directory
      • It is worth mentioning that there are three directories mounted in Code God's notes , namely configuration files, logs, and data files. I keep getting errors in the log in actual operation, so I just configure only the most important data files
    • The next step is to specify the default password of the host MySQL. If the default password is not set, an error may be reported.
docker run -id \
-p 3307:3306 \
--name=mysql \
-v /mnt/docker/mysql/data:/var/lib/mysql \
-e MYSQL_ROOT_PASSWORD=root \
mysql:5.7

Mapping files with mounts

Next we need to enter the container and open permissions

  • docker psCheck if the container is already running
    • You should see that the mysql5.7 container is already running
  • into the containerdocker exec -it mysql bash
  • MYSQL into the containermysql -uroot -p
    • Enter the password, as above, I set it as root, just enter it directly. (Blank is displayed on the interface, but the password has already been entered, press Enter to confirm.)
  • The next steps are similar to step 10 of installing the host mysql above
    • show databases;
    • use mysql ;
    • show tables;
    • select user,host from user;(It may report an sql error, just add the `` package field)
      • It can be seen that the host corresponding to the root user is not %, we have to change it to % to open permissions.
    • update user set host ='%'where user ='root';
    • update user set host ='%'where user ='root' and host='localhost';
    • It is best to execute both sentences. In my situation at the time, there were two root users. The result of the execution was that one root corresponding to the host was empty, and the other host was %.
    • (You can even open advanced permissions grant all privileges on *.* to root@'%' identified by 'root' with grant option;)
    • Refresh permissionsflush privileges;
  • exitExit MySQL, and then exitexit the MySQL container

Check whether the Docker container of mysql is successfully configured, and view its exposed docker ip address

  • Use this docker logs -f mysqlto see if the configuration is successfulinsert image description here
  • docker inspect mysql→ Check the ip address 172.17.0.2 of the corresponding mysql docker container, please remember this address, which is needed for the packaging background application below.
    The ip address of the MySQL Docker container

After the environment is correct, we need to import our database file blog.sql

  • As mentioned above, we have implemented the mapping between the host /mnt/docker/mysql/datadirectory and the /var/lib/mysqladdress of the docker container. Therefore, if we import the blog.sql file into this directory of the host, blog.sql will also appear in the corresponding directory of docker. Below, the specific operations are as follows:
cd /mnt/docker/mysql/data
rz
  • Among them, cd means to switch directories, and rz means to upload files. At this point, we can import blog.sql into it. Next we check if the file appears in the docker container
  • into the containerdocker exec -it mysql bash
  • Change to the mount directorycd /var/lib/mysql
  • Looking at all the files lsin this directory, you can theoretically see that blog.sql is also in this directory.
  • Next execute the sql in docker.
    • mysql -uroot -p, enter the password to enter the database in docker
    • create databasecreate database blog;
    • exit back to the containerexit
    • Import file into databasemysql -uroot -p blog < blog.sql;
    • switch databaseuse blog;
    • execute sql and save the databasesource blog.sql;
  • result check
    • use blog; show tables; select * from ms_admin;
    • If we can find the result (as shown in the figure below), it means that our deployment was successful.
      Database data successfully imported
  • In the actual deployment, I spend the most time on the database, such as link failure, access denied, jdbc connection failed, etc., most likely because of database permissions. Please check whether the host permissions corresponding to root are % these.
  • There is also a database configuration file written in Code God's notes, I didn't write it here, just use the default configuration for the time being.

4 docker configure redis

  • This is very simple, one command to do it
  • docker run -id --name=redis -p 6379:6379 redis:5.0.3
  • an examination
    • docker ps View the currently running container, in theory, now you can see that both mysql and redis are running.
    • docker ps -a View all containers (including not running)
  • We need to check the ip address corresponding to redis docker, which docker inspect rediswill be used later when packaging the project. Here I am 172.17.0.3
    The ip address corresponding to redis docker

5 Dockerfile builds backend image

  • We can directly pull the mirrors such as MySQL and redis, but the mirrors of the back-end projects need to be packaged and built by ourselves.
  • Code God's explanation of Dockerfile is as follows
    • Dockerfile is a text file
    • contains a command
    • Each instruction builds a layer, based on the base image, and finally builds a new image
    • For developers: can provide a completely consistent development environment for the development team
    • For testers: you can directly take the image built during development or
      build a new image through the Dockerfile file to start working
    • For operation and maintenance personnel: seamless migration of applications can be achieved during deployment

First, we need to configure the parameters on the idea and package

  • Configure connection parameters -idea configuration
  • There is also a parameter about cross-domain configuration. You can also refer to the following. You need to allow your own domain to pass, and then the cross-domain configuration is changed from the one written by the teacher to the second one. The reason is as shown in the figure, please Attention everyone! insert image description here- Package and generate jar packagePackaging configuration
  • Find the local file, put it in a good place to find it, and prepare to import it into our directory later
    Packed file processing

Next, we need to import the jar package in the /mnt/docker/app directory, build the configuration file of the image and run the image.

  • Create a new directory firstmkdir /mnt/docker/app
  • Configurations that can use the upload functionyum -y install lrzsz
  • switch to this directorycd /mnt/docker/app
  • upload filesrz
  • change namemv blog-api-1.0-SNAPSHOT.jar blog_api.jar
  • Configure the configuration file for building the image
    • create a new filetouch blog_dockerfile
    • Modify file contentvim blog_dockerfile
    • Paste the following content into it (modify the personal parameters yourself)
FROM java:8
MAINTAINER zhangshidi <[email protected]>
ADD ./blog_api.jar /app.jar
CMD java -jar /app.jar --spring.profiles.active=prod
  • run imagedocker build -f ./blog_dockerfile -t app .
  • Check, docker imagesyou should see that the app's docker is already running

6 Build the front-end image

Modify the front-end configuration, package, upload, and fine-tune file locations.

  • Let's go to the front

    • modify ipinsert image description here
  • Build the project, he will automatically generate the project to dist, manually compress the file and send it to our cloud server.insert image description here

  • Back to the command window interface, we should install the unzip function

#获取安装列表  yum安装列表中搜索zip/unzip是否存在

yum list | grep zip/unzip

#执行安装支持zip命令 根据提示输入y允许安装

yum install zip

#执行安装支持unzip命令 根据提示输入y允许安装

yum install unzip
  • Create the corresponding folder
    • mkdir /mnt/zhang
    • mkdir /mnt/zhang/blog
  • Switch to the blog directory cd /mnt/zhang/blog
    - upload rz, upload our front-end dist compressed package
  • decompressunzip dist.zip
  • Then move the file location, under /mnt/zhang/blog ls, it should be the following three files: dist.zip, index.html, static, in fact, the useful ones should be index.html and static
    • As for how to move, I dragged it directly on the file directory on the left. You can also find the corresponding command.
      insert image description here

7 Docker-compose service orchestration

  • Service orchestration mainly uses Docker Compose to start springboot and nginx in batches
    • Springboot is our own packaged project
    • The role of nginx: ① The static files (such as HTML, pictures) on the server are displayed to the client through the HTTP protocol. ②Reverse proxy server, where nginx proxy is the front-end resource client can directly access a website application server through HTTP protocol, the website administrator can add a Nginx in the middle, the client requests Nginx, Nginx requests the application server, and then the The result is returned to the client. Adding a layer of proxy can achieve load balancing, virtual hosting and other effects. ( please see for details )

First, we install Docker Compose

# Compose目前已经完全支持Linux、Mac OS和Windows,在我们安装Compose之前,需要先安装Docker。下面我 们以编译好的二进制包方式安装在Linux系统中。 
curl -L https://github.com/docker/compose/releases/download/1.22.0/docker-compose-`uname -s`-`uname -m` -o /usr/local/bin/docker-compose
# 设置文件可执行权限 
chmod +x /usr/local/bin/docker-compose
# 查看版本信息 
docker-compose -version

Create the corresponding directory and write the docker-compose.yml configuration file

  • vimmeans to modify the file
mkdir /mnt/docker/docker-compose
cd /mnt/docker/docker-compose
touch docker-compose.yml
vim docker-compose.yml
  • Copy the following content to docker-compose.yml. After writing, press Esc to exit the editing mode, and then enter :wq, you can save and exit~
version: '3'
services:
  nginx:
   image: nginx
   container_name: nginx
   ports:
    - 80:80
    - 443:443
   links:
     - app
   depends_on:
    - app
   volumes:
    - /mnt/docker/docker-compose/nginx/:/etc/nginx/
    - /mnt/zhang/web:/zhang/web
    - /mnt/zhang/blog:/zhang/blog
   network_mode: "bridge"
  app:
    image: app
    container_name: app
    expose:
      - "8888"
    network_mode: "bridge"
  • This file has depends_onthe function of arranging directories. Regarding this mount directory, please pay attention to your own directory order. When following various tutorials, you should distinguish their directory order from your own directory order. The following is my directory order
    insert image description here

Next, we need to configure the nginx file directory and related internal configuration files

  • First, we need to get the nginx.conffile
mkdir -p ./nginx
cd /mnt/docker/nginx
touch nginx.conf
vim nginx.conf
  • Copy the following content
user nginx;
worker_processes  1;
error_log  /var/log/nginx/error.log warn;
pid        /var/run/nginx.pid;
events {
    worker_connections  1024;
}
http {
    include       /etc/nginx/mime.types;
    default_type  application/octet-stream;
    log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                      '$status $body_bytes_sent "$http_referer" '
                      '"$http_user_agent" "$http_x_forwarded_for"';
    access_log  /var/log/nginx/access.log  main;
    sendfile        on;
    #tcp_nopush     on;
    keepalive_timeout  65;
    #gzip  on;
    include /etc/nginx/conf.d/*.conf;
}
  • Create a new conf.d folder, and then create a new blog.conffile
mkdir conf.d
cd conf.d
touch blog.conf
vim blog.conf

blog.confModify the configuration and put the following files into

gzip_min_length 1k;
gzip_buffers 4 16k;
gzip_comp_level 2;
gzip_vary off;
upstream appstream{
     
        server app:8888;
}
server{
    # 监听端口
    listen  80;
    # 主机名称/地址
    server_name www.zhangshidi.space zhangshidi.space;
    index   index.html;
    # 前端服务
     location / {
        root /zhang/blog/;
        # 刷新页面后跳转到当前页面
        try_files $uri $uri/ /index.html;
        index index.html;
     }

     # 后端api
     location /api {
                proxy_pass http://appstream;
    }

    location ~* \.(jpg|jpeg|gif|png|swf|rar|zip|css|js|map|svg|woff|ttf|txt)$ {
        root /zhang/blog/;
        index index.html;
        add_header Access-Control-Allow-Origin *;
    }
}
  • There is also a ssl/tsl configuration in the configuration of the code god . If you need it, you can apply for it and then configure it. I will omit it here.

  • You can see that there is also a file calledmime.types
  • This thing is a must-have in nginx. I downloaded an nginx from the Internet, took out the mime.typesfile , and rzentered it. You can also create a new file and copy the code into it. The code is as follows.

types {
    text/html                                        html htm shtml;
    text/css                                         css;
    text/xml                                         xml;
    image/gif                                        gif;
    image/jpeg                                       jpeg jpg;
    application/javascript                           js;
    application/atom+xml                             atom;
    application/rss+xml                              rss;

    text/mathml                                      mml;
    text/plain                                       txt;
    text/vnd.sun.j2me.app-descriptor                 jad;
    text/vnd.wap.wml                                 wml;
    text/x-component                                 htc;

    image/png                                        png;
    image/svg+xml                                    svg svgz;
    image/tiff                                       tif tiff;
    image/vnd.wap.wbmp                               wbmp;
    image/webp                                       webp;
    image/x-icon                                     ico;
    image/x-jng                                      jng;
    image/x-ms-bmp                                   bmp;

    font/woff                                        woff;
    font/woff2                                       woff2;

    application/java-archive                         jar war ear;
    application/json                                 json;
    application/mac-binhex40                         hqx;
    application/msword                               doc;
    application/pdf                                  pdf;
    application/postscript                           ps eps ai;
    application/rtf                                  rtf;
    application/vnd.apple.mpegurl                    m3u8;
    application/vnd.google-earth.kml+xml             kml;
    application/vnd.google-earth.kmz                 kmz;
    application/vnd.ms-excel                         xls;
    application/vnd.ms-fontobject                    eot;
    application/vnd.ms-powerpoint                    ppt;
    application/vnd.oasis.opendocument.graphics      odg;
    application/vnd.oasis.opendocument.presentation  odp;
    application/vnd.oasis.opendocument.spreadsheet   ods;
    application/vnd.oasis.opendocument.text          odt;
    application/vnd.openxmlformats-officedocument.presentationml.presentation
                                                     pptx;
    application/vnd.openxmlformats-officedocument.spreadsheetml.sheet
                                                     xlsx;
    application/vnd.openxmlformats-officedocument.wordprocessingml.document
                                                     docx;
    application/vnd.wap.wmlc                         wmlc;
    application/x-7z-compressed                      7z;
    application/x-cocoa                              cco;
    application/x-java-archive-diff                  jardiff;
    application/x-java-jnlp-file                     jnlp;
    application/x-makeself                           run;
    application/x-perl                               pl pm;
    application/x-pilot                              prc pdb;
    application/x-rar-compressed                     rar;
    application/x-redhat-package-manager             rpm;
    application/x-sea                                sea;
    application/x-shockwave-flash                    swf;
    application/x-stuffit                            sit;
    application/x-tcl                                tcl tk;
    application/x-x509-ca-cert                       der pem crt;
    application/x-xpinstall                          xpi;
    application/xhtml+xml                            xhtml;
    application/xspf+xml                             xspf;
    application/zip                                  zip;

    application/octet-stream                         bin exe dll;
    application/octet-stream                         deb;
    application/octet-stream                         dmg;
    application/octet-stream                         iso img;
    application/octet-stream                         msi msp msm;

    audio/midi                                       mid midi kar;
    audio/mpeg                                       mp3;
    audio/ogg                                        ogg;
    audio/x-m4a                                      m4a;
    audio/x-realaudio                                ra;

    video/3gpp                                       3gpp 3gp;
    video/mp2t                                       ts;
    video/mp4                                        mp4;
    video/mpeg                                       mpeg mpg;
    video/quicktime                                  mov;
    video/webm                                       webm;
    video/x-flv                                      flv;
    video/x-m4v                                      m4v;
    video/x-mng                                      mng;
    video/x-ms-asf                                   asx asf;
    video/x-ms-wmv                                   wmv;
    video/x-msvideo                                  avi;
}
  • check, use lsinstruction
    insert image description here

8 Run the test

  • At this point, our deployment is basically complete

  • Also docker pscheck, 4 containers are runninginsert image description here

  • Switch to the docker-compose directory and start the container. The following are some common instructions for starting and stopping containers.

docker-compose up #直接启动

docker-compose up -d #代表后台启动

docker-compose down  #停止并删除容器

docker-compose start #启动已有容器

docker-compose stop  #停止运行的容器
  • Generally speaking, we docker-compose upstart directly to see if there is any problem with the website. If there is a problem, use the following two commands to improve it.
    • Check out the ngix log:docker logs nginx
    • View backend logs:docker-compose logs
  • When we feel that the deployment is completely done, we can start docker-compose up -d in the background, so that the server can be turned off and run.

  • Finally, I would like to thank the two article ideas I referenced. They are both well written, but some details are difficult for me to implement here. I also want to thank Mr. Code God for his efforts. You can also refer to and compare them, I believe they will help you. Inspired.
  • There is another question, you may ask why there is no background management deployment?
    • Let's take a closer look at the background management. It can only be said to be a case of Spring Security, and it does not play the role of background management at all... Although it is deployed, it is meaningless.

Thank you for your visit. If you think the writing is good, please give a like and encouragement. If you have any questions, please leave a message. Welcome to point out the problem.

  • Also set a flag for yourself, then learn Spring Cloud, and then go to conquer the mall project with the most stars on github

Guess you like

Origin blog.csdn.net/dolpin_ink/article/details/123056852