Experience in using docker

Please point out the deficiencies in the first compilation.

Use docker (docker-compose.yml) and nginx to run the springboot project on linux. java, mysql, redis and nginx are running on docker, so you don't need to install them locally. Learn to use them

Installing docker for linux

  1. Install docker command:

curl -fsSL https://get.docker.com | bash -s docker --mirror Aliyun

  1. To install the docker compose command:

sudo curl -L "https://github.com/docker/compose/releases/download/1.27.4/docker-compose- ( u n a m e − s ) − (uname -s)- (uname−s)−(uname -m)" -o /usr/local/bin/docker-compose

  1. Set Compose to executable:

sudo chmod +x /usr/local/bin/docker-compose

  1. To create a soft chain:

sudo ln -s /usr/local/bin/docker-compose /usr/bin/docker-compose

  1. Test whether Compose is successfully installed:

docker-compose --version

  1. Start docker:

sudo systemctl start docker

  1. Set startup and self startup:

systemctl enable docker.service

After installation, test it

  1. function

sudo docker run hello-world

  1. Then I reported the following error, saying that our docker did not start
Cannot connect to the Docker daemon at unix:///var/run/docker.sock. Is the docker daemon running?.
  1. Then I started it again and ran: > sudo systemctl start docker
  2. If the following contents pop up, docker can run normally:
Digest: sha256:9ade9cc2e26189a19c2e8854b9c8f1e14829b51c55a630ee675a5a9540ef6ccf
Status: Downloaded newer image for hello-world:latest

Set compose to run nginx, java, mysql and redis

  1. When writing docker-compose.yml, pay attention to the name of the file. Some attached things in the following contents will be explained later
version: "1"
  nginx: # Service name, user defined
    image: nginx:latest  # Mirror version
    container_name: nginx  #Start alias
    restart: always #The service will be started automatically when docker is started
    network_mode: host #No longer corresponds to a port, I think the explanation is corresponding to all ports
    volumes: # Mount to the specific files on the local server (the specific local directories and files in the front can be changed according to your own needs, and the ones on docker in the back)
      - /home/docker/nginx/www:/usr/share/nginx/html
      - /home/docker/nginx/conf/nginx.conf:/etc/nginx/nginx.conf
      - /home/docker/nginx/cer:/usr/share/nginx/cer
    privileged: true # This must solve the permission problem of file call of nginx
    image: mysql:5.7
    container_name: mysql
    restart: always
      - 3306:3306
      - /home/mysql/conf.d:/etc/mysql/conf.d
      - /home/mysql/mysql:/var/lib/mysql
    environment: # Specifies the password of the user root
      - TZ=Asia/Shanghai
      - MYSQL_ROOT_PASSWORD=123456 #Set the password for mysql
    image: redis:latest
    container_name: redis
    restart: always
      - 6379:6379
      - /home/redis/redis.conf:/etc/redis/redis.conf
      - /home/redis/data:/data
      - TZ=Asia/Shanghai
    command: redis-server --requirepass 123456 --appendonly yes
    build: . # Indicates that the image is built from the Dockerfile in the current directory
    image: vuestudy:latest
    restart: always
    container_name: vuestudy
      - 8080:8080
      - /home/docker/vuestudy.jar:/home/first/vuestudy.jar
    image: vuestudy:latest
    restart: always
    container_name: vuestudy2
      - 8081:8080
      - /home/docker/vuestudy.jar:/home/first/vuestudy.jar

  1. Write Dockerfile, and the file name must also be this
FROM java:8
RUN /bin/cp /usr/share/zoneinfo/Asia/Shanghai /etc/localtime && echo 'Asia/Shanghai' >/etc/timezone
ENTRYPOINT ["java","-jar", "/home/first/vuestudy.jar", "--server.port=8080", "--spring.profiles.active=prod"]
  1. Explain the mounting of docker in detail
  • Dockerfile is equivalent to creating a docker image. Run the springboot project under this image. If the directories are different, you need to modify them yourself
  • mysql mount is to map the mysql data on the docker to the local, and then delete the mysql image on the docker. I mapped mysql to the local * * / home/mysql * * folder. After creating the folder, run the command to copy the required data to the local, but we haven't started mysql yet, so we need to run mysql first:

docker run -d -p 3306:3306 -e MYSQL_ROOT_PASSWORD=123456 --name mysql mysql:5.7

  • After mysql runs successfully

    1. After running, you can use docker ps to view the running container status and docker exec -it cmysql bash to enter the container. However, we only need to copy what we need to do locally. Run the following command to copy it:

      docker cp mysql:/etc/mysql/conf.d /home/mysql/

      docker cp mysql:/var/lib/mysql /home/mysql/

    2. After replication, stop deleting the mysql container and then delete the image:

      docker stop $(docker ps -aq) / / stop all containers

      sudo docker rm $(sudo docker ps -a -q) / / delete all non running containers

      docker rmi $(docker images -q) / / delete all images

    3. However, I have problems with the time and coding of mysql in subsequent use. I go back and modify the following configuration. If you encounter it, you can modify it here and enter the local * * / home/mysql/conf.d * * directory, vi Write my.cnf file:
      default-time-zone = '+08:00'
      lower_case_table_names = 1
  • Redis is the same as mysql, but it does not need to run. Create a folder, create a data directory under the local * * / home/redis, and download the file redis.conf Then modify the following contents and put them into the redis * * folder:

    1. bind # comments out this part, which restricts redis to local access
    2. Daemon no # set to no
    3. Protected mode no # defaults to yes. The protected mode is enabled and local access is restricted
    4. requirepass 123456 # whether a password is required, and it is not necessary to comment it out
  • Mounting of nginx

    1. /home/docker/nginx/www creates a file directory locally. It is used to place static resource files so that local static data can be called after the nginx container is started
    2. /home/docker/nginx/cer this folder is created locally to place the CER certificate. When using https, you need to call
    3. /home/docker/nginx/conf/nginx.conf is the most critical configuration of nginx. We also put it locally for easy modification. The following is the content of nginx.conf. When writing nginx.conf, don't copy it directly after windows. It will be garbled. It's best to write and copy it with vi command, and modify it appropriately according to your own needs
      #The nx worker process runs users and user groups, and the default nobody account runs
      user  nginx;
      #worker_processes specifies the number of sub processes to be started by nginx. Each process is monitored during operation
      #The memory consumption (generally ranging from a few m to tens of M) is adjusted according to the actual situation. Usually, the number is an integer multiple of the number of CPU cores
      worker_processes  2;
      #Define the location and output level of the error log file [debug / info / notice / warn / error / crit]
      #error_log  logs/error.log;
      #error_log  logs/error.log  notice;
      error_log  /var/log/nginx/error.log warn;
      #The location of the storage file used to specify the process id
      pid        /var/run/nginx.pid;
      #A description that specifies the maximum number of files a process can open
      worker_rlimit_nofile 65535;
      worker_cpu_affinity 01 10;
      #Some operation configurations for the working mode of nginx server
      events {
      #Specify the maximum number of connections that can be received at the same time. It must be noted here that the maximum number of connections is determined jointly with worker processes.
      worker_connections  51200;
      #The configuration specifies that nginx accepts as many connections as possible after receiving a new connection notification
      #multi_accept on;
      #The configuration specifies the method of thread polling. If it is Linux 2.6 +, use epoll. If it is BSD, such as Mac, use Kqueue
      use epoll;
      #As a web server, http module is the core module of nginx
      http {
          # Basic configuration
          #Configure on to let sendfile play its role, and let the file write back process be completed by the data buffer rather than in the application. In this way, it is beneficial to improve the performance
          sendfile on;
              #Let nginx send all header files in one packet instead of sending them separately
          #tcp_nopush on;
              #Let nginx not cache data, but send it section by section. If the data transmission has real-time requirements, you can configure it. After sending a small section of data, you can get the return value immediately, but don't abuse it
          tcp_nodelay on;
              #Assign a connection timeout to the client, after which the server will close the connection. Generally, the setting time is short, which can make nginx work more continuously
          keepalive_requests 50000;
          keepalive_timeout 1000;
              #Confusing data will affect the three column conflict rate. The larger the value, the more memory will be consumed, the hash key conflict rate will be reduced and the retrieval speed will be faster; The smaller the key value, the less memory it takes, the higher the collision rate, and the slower the retrieval speed
          types_hash_max_size 2048;
              #Although it will not make nginx execute faster, you can turn off the nginx version prompt on the error page, which is good for improving the security of the website
          # server_tokens off;
          # server_names_hash_bucket_size 64;
          # server_name_in_redirect off;
          #Specifies the directive to include another file in the current file
          include       /etc/nginx/mime.types;
          #Specifies that the file type processed by default can be binary
          default_type  application/octet-stream;
      	proxy_intercept_errors on;
          log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                            '$status $body_bytes_sent "$http_referer" '
                            '"$http_user_agent" "$http_x_forwarded_for"';
          # Log configuration
          #Set the log that stores access records
          access_log  /var/log/nginx/access.log  main;
          #Set the log where storage records the occurrence of errors
          error_log   /var/log/nginx/error.log;
          # SSL certificate configuration
              #The instruction is used to start a specific encryption protocol. nginx defaults to SSL after versions 1.1.13 and 1.0.12_ protocols SSLv3 TLSv1 TLSv1.1 TLSv1.2,
              #TLSv1.1 and TLSv1.2 should ensure that OpenSSL > = 1.0.1. SSLv3 is still used in many places, but there are many exploited vulnerabilities.
          #ssl_protocols TLSv1 TLSv1.1 TLSv1.2; # Dropping SSLv3, ref: POODLE
              #When setting the negotiation encryption algorithm, we give priority to the encryption suite of our server rather than the encryption suite of the client browser
          #ssl_prefer_server_ciphers on;
          # Gzip compression configuration
          #Is to tell nginx to send data in the form of gzip compression. This will reduce the amount of data we send.
           gzip  on;
              #Disable gzip functionality for the specified client. We set it to IE6 or lower to make our solution widely compatible.
               gzip_disable "msie6";
              #The upstream module is mainly responsible for the configuration of load balancing, and distributes requests to the back-end server through the default polling scheduling method
              upstream tomcatserver1 {
                              #Specify the request scheduling algorithm. The default is weight weight polling scheduling, which can be specified
                              #ip_hash;  Each request is allocated according to the hash result of the access IP (i.e. the front server or client IP of Nginx),
                              #In this way, each visitor will access a back-end server, which can solve the problem of session consistency.
                              #server host:port: the list configuration of the distributor. is the address of my server. You need to change it to your own
                              server weight=1 max_fails=2 fail_timeout=10s;
                              server weight=1 max_fails=2 fail_timeout=10s;
                              #down: indicates that the host is out of service
                              #max_ Failures: indicates the maximum number of failures. If the maximum number of failures is exceeded, the service will be suspended
                              #fail_timeout: indicates that if the request acceptance fails, the request will be restarted after the specified time is suspended
          #Configuration of a virtual host. Multiple server s can be configured in one http
          #Host configuration
      	server {
              #Listen to the port number. If you use 80, the domain name can not add the port number
              listen       80;
                      #It is used to specify the ip address or domain name. Multiple configurations are separated by spaces. If you run locally, you need to change the host file of the computer to configure www.xx.com
                      #How to change the host: add a DNS record www.helloworld.com to the host file in the directory C:\Windows\System32\drivers\etc
              #Used to set the default encoding format of web pages configured in the www / path
              charset        utf-8;
      		#This is the static file address of the container. Because mount is used above, we will access our local www folder
              location /love {
                      alias /usr/share/nginx/html;
                      index index.html;
              #Reverse proxy server access mode through proxy_set configuration makes client access transparent
              location / {
      			#Tomcat Server1 needs to be the same as the above. You can choose any name as long as it is the same
                   proxy_pass    http://tomcatserver1;
                         proxy_redirect    off;
                         proxy_set_header   Host $host:80;
                         proxy_set_header   X-Real-IP $remote_addr;
                         proxy_set_header   X-Forwarded-For $proxy_add_x_forwarded_for;
                         client_max_body_size   1024m;
                         client_body_buffer_size   1024k;
                         proxy_connect_timeout   15;
                         proxy_send_timeout   15;
                         proxy_read_timeout   15;
                         proxy_buffer_size   8k;#
                         proxy_buffers   4 64k;
                         proxy_busy_buffers_size   128k;
                         proxy_temp_file_write_size  128k;
              # redirect server error pages to the static page /50x.html
              #error_page   500 502 503 504  /50x.html;
              #location = /50x.html {
              #    root   html;
      	#This is my https. You can delete it if you don't need it
          server {
               listen 443 ssl;
               server_name localhost;
               root html;
               index index.html index.htm;
               ssl_certificate /usr/share/nginx/cer/cert-file-name.pem;   #You need to replace cert-file-name.pem with the name of the uploaded certificate file.
               ssl_certificate_key /usr/share/nginx/cer/cert-file-name.key;   #You need to replace cert-file-name.key with the name of the uploaded certificate key file.
               ssl_session_timeout 5m;
               ssl_ciphers ECDHE-RSA-AES128-GCM-SHA256:ECDHE:ECDH:AES:HIGH:!NULL:!aNULL:!MD5:!ADH:!RC4;
               ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
               ssl_prefer_server_ciphers on;
               location / {
                   proxy_pass    http://tomcatserver1;
                         proxy_redirect    off;
                         proxy_set_header   Host $host:80;
                         proxy_set_header   X-Real-IP $remote_addr;
      				   proxy_set_header   X-Forwarded-For $proxy_add_x_forwarded_for;
                         client_max_body_size   1024m;
                         client_body_buffer_size   1024k;
                         proxy_connect_timeout   15;
                         proxy_send_timeout   15;
                         proxy_read_timeout   15;
                         proxy_buffer_size   8k;#
                         proxy_buffers   4 64k;
                         proxy_busy_buffers_size   128k;
                         proxy_temp_file_write_size  128k;
  • Everything is ready. Next, create the docker folder in the home directory, then put the docker-compose.yml, Dockerfile, vuesetudy.jar (springboot project) into the docker folder, and then create the nginx folder here. The directory structure is as follows:

  • Last run

    cd /home/docker / / enter the yml file directory

    Docker compose up - D / / execute compose

  1. After the above steps run normally and successfully, you can use docker ps to check the running status of the container, and the project will start. You can try to access it. The above directory structure picture is in the static folder www I put above. You can access it successfully

Finally, let's summarize the common commands of docker

systemctl restart docker / / restart docker

Docker exec < container ID > / / enter the container

docker attach container name or container ID bash / / enter the container

docker exec -it container name or container ID bash / / enter the container

docker run -d -p 3306:3306 -e MYSQL_ ROOT_ Password = 123456 -- name MySQL: 5.7 / / start the container

docker ps (-a) all (- l) last / / view container operation

docker logs #id / / view the log output in the container

docker stop #id / / stop container

docker # instruction -- help / / view the instruction details

docker pull # container name (ubuntu) / / get the image container

docker start #id / / start a stopped container

Docker restart < container ID > / / restart the container

Docker export < container ID > ubuntu.tar / / export container

Docker RM - f < container ID > / / delete container

docker images / / lists the images

Docker search < image name > (httpd) / / query the image

Docker RMI < image name > (Hello word) / / delete the image

docker exec -it mysql /bin/bash / / enter the container

mysql -h localhost -u root -p / / enter the MySQL container and then enter mysql

That's the end of the first use of docker. Please point out the problems and errors. Thank you

Tags: Java Linux Operation & Maintenance Docker Nginx

Posted on Tue, 12 Oct 2021 03:32:33 -0400 by sc00tz