Table of Contents
Run the mysql instance first (do not directly docker-compose up -d to run all instances)
Home Database Mysql Tutorial How to use dockercompose to build nginx+mysql+redis+springboot project

How to use dockercompose to build nginx+mysql+redis+springboot project

May 27, 2023 pm 09:20 PM
mysql nginx dockercompose

Please install docker and docker-compose in advance and configure image acceleration yourself.

A.docker-compose.yml file

version: "3"
services:
  nginx: # 服务名称,用户自定义
    image: nginx:latest  # 镜像版本
    ports:
      - 80:80  # 暴露端口
    volumes: # 挂载
      - /root/nginx/html:/usr/share/nginx/html
      - /root/nginx/nginx.conf:/etc/nginx/nginx.conf
    privileged: true # 这个必须要,解决nginx的文件调用的权限问题
  mysql:
    image: mysql:5.7.27
    ports:
      - 3306:3306
    environment: # 指定用户root的密码
      - MYSQL_ROOT_PASSWORD=
  redis:
    ports:
      - 6379:6379
    image: redis:latest
  vueblog:
    image: vueblog:latest
    build: . # 表示以当前目录下的Dockerfile开始构建镜像
    ports:
      - 81:81
    depends_on: # 依赖与mysql、redis,其实可以不填,默认已经表示可以
      - mysql
      - redis


  nacos1:
    hostname: nacos1
    container_name: nacos1
    image: nacos/nacos-server:latest
    volumes:
      # 需要添加mysql8的插件
      #- ./nacos/plugins/mysql/:/home/nacos/plugins/mysql/
      # 把日志文件映射出来
      - /root/nacos1:/home/nacos/logs
      # 把配置文件映射出来
      - /root/nacos1/custom.properties:/home/nacos/init.d/custom.properties

    environment: # 设置环境变量,相当于docker run命令中的-e
      - JVM_XMS=512m
      - JVM_XMX=512m
      - JVM_XMN=128m
      #- MODE=standalone   #单机版
    ports:
      - "8848:8848"
    env_file:
      # 集群配置文件
      - /root/nacos1/nacos-hostname.env
    restart: always
    depends_on:
      - mysql
Copy after login

B.springboot configuration (own project)

The mysql and redis configurations in the configuration are both used Service name instead of ip address

server:
  port: 81


spring:
  servlet:
    multipart:
      max-file-size: 10MB
      max-request-size: 10MB
  profiles:
    active: dev
  # mysql 配置
  datasource:
      url: jdbc:mysql://mysql:3306/blog4?serverTimezone=GMT%2B8&useUnicode=true&characterEncoding=UTF-8
      username: 
      password: 
#      schema: classpath:springbootsecurityauth.sql
      sql-script-encoding: utf-8
      initialization-mode: always
      driver-class-name: com.mysql.cj.jdbc.Driver
      type: com.alibaba.druid.pool.DruidDataSource
      # 初始化大小,最小,最大
      initialSize: 1
      minIdle: 3
      maxActive: 20
     # 配置获取连接等待超时的时间
      maxWait: 60000
      # 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒
      timeBetweenEvictionRunsMillis: 60000
      # 配置一个连接在池中最小生存的时间,单位是毫秒
      minEvictableIdleTimeMillis: 30000
      validationQuery: select 'x'
      testWhileIdle: true
      testOnBorrow: false
      testOnReturn: false
      # 打开PSCache,并且指定每个连接上PSCache的大小
      poolPreparedStatements: true
      maxPoolPreparedStatementPerConnectionSize: 20
      # 配置监控统计拦截的filters,去掉后监控界面sql无法统计,'wall'用于防火墙 ,slf4j
      filters: stat,wall,slf4j
      # 通过connectProperties属性来打开mergeSql功能;慢SQL记录
      connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000

  redis:
    database: 6
    host: redis
    port: 6379
    timeout: 5000s  # 连接超时时长(毫秒)
    jedis:
      pool:
        max-active: 20 #连接池最大连接数(使用负值表示没有限制)
        max-idle: 8  #连接池中的最大空闲连接
        max-wait: -1s #连接池最大阻塞等待时间(使用负值表示没有限制)
        min-idle: 0  #连接池中的最小空闲连接
    password:  #rootroot
Copy after login

C.Dockerfile

FROM java:8
EXPOSE 81
ADD vueblog.jar app.jar
RUN bash -c 'touch /app.jar'
ENTRYPOINT ["java", "-jar", "/app.jar"]
Copy after login

D. Package the springboot project and name it the service name in the configuration

E. In the corresponding Create a folder or file under the directory

- /root/nginx/html
- /root/nginx/nginx.conf

#user  root;
worker_processes  1;
events {
    worker_connections  1024;
}
http {
    include       mime.types;
    default_type  application/octet-stream;
    sendfile        on;
    keepalive_timeout  65;

   #这里配置nacos的ip:端口,因为nginx和nacos在同一个网络下,这里可以用服务名访问
   upstream nacos {
        server nacos1:8848 weight=1 max_fails=2 fail_timeout=10s;
        #server nacos2:8848 weight=1 max_fails=2 fail_timeout=10s;
        #server nacos3:8848 weight=1 max_fails=2 fail_timeout=10s;
    }

    server {
        listen       80;
        server_name  localhost;

        location / {
            root   /usr/share/nginx/html/front;
            try_files $uri $uri/ /index.html last; # 别忘了这个哈
            index  index.html index.htm;
        }

       location /admin {
	    alias /usr/share/nginx/html/admin;
	    expires  1d;
	    index index.html;
	    autoindex on;
        }

        location /nacos {
            proxy_pass   http://nacos;
            proxy_set_header Host $host;
            proxy_set_header X-Real-IP $remote_addr;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
            proxy_set_header REMOTE-HOST $remote_addr;
            add_header X-Cache $upstream_cache_status;
            add_header Cache-Control no-cache;
        }

        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
            root   html;
        }
    }
}
Copy after login

- /root/nacos1
# Configure File mapping
- /root/nacos1/custom.properties

#spring.security.enabled=false
#management.security=false
#security.basic.enabled=false
#nacos.security.ignore.urls=/**
#management.metrics.export.elastic.host=http://localhost:9200
# metrics for prometheus
management.endpoints.web.exposure.include=*

# metrics for elastic search
#management.metrics.export.elastic.enabled=false
#management.metrics.export.elastic.host=http://localhost:9200

# metrics for influx
#management.metrics.export.influx.enabled=false
#management.metrics.export.influx.db=springboot
#management.metrics.export.influx.uri=http://localhost:8086
#management.metrics.export.influx.auto-create-db=true
#management.metrics.export.influx.consistency=one
#management.metrics.export.influx.compressed=true
Copy after login

- /root/nacos1/nacos-hostname.env

Configure nacos database information

#nacos dev env
PREFER_HOST_MODE=hostname
NACOS_SERVERS=nacos1:8848
MYSQL_SERVICE_HOST=mysql
MYSQL_SERVICE_DB_NAME=nacos
MYSQL_SERVICE_PORT=3306
MYSQL_SERVICE_USER=
MYSQL_SERVICE_PASSWORD=
JVM_XMS=512m
JVM_XMX=512m
JVM_XMN=256m
JVM_MS=64m
JVM_MMS=128m
Copy after login

The final directory structure

How to use dockercompose to build nginx+mysql+redis+springboot project

Run the mysql instance first (do not directly docker-compose up -d to run all instances)

docker-compose up -d mysql
Copy after login

F. Since my nacos was added later, you can add the nacos database in the mysql container in advance and then start it (if you do not have a database, please add it in advance)

Start

docker-compose up
Copy after login

Stop

docker-compose down
Copy after login

The above is the detailed content of How to use dockercompose to build nginx+mysql+redis+springboot project. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PHP's big data structure processing skills PHP's big data structure processing skills May 08, 2024 am 10:24 AM

Big data structure processing skills: Chunking: Break down the data set and process it in chunks to reduce memory consumption. Generator: Generate data items one by one without loading the entire data set, suitable for unlimited data sets. Streaming: Read files or query results line by line, suitable for large files or remote data. External storage: For very large data sets, store the data in a database or NoSQL.

How to optimize MySQL query performance in PHP? How to optimize MySQL query performance in PHP? Jun 03, 2024 pm 08:11 PM

MySQL query performance can be optimized by building indexes that reduce lookup time from linear complexity to logarithmic complexity. Use PreparedStatements to prevent SQL injection and improve query performance. Limit query results and reduce the amount of data processed by the server. Optimize join queries, including using appropriate join types, creating indexes, and considering using subqueries. Analyze queries to identify bottlenecks; use caching to reduce database load; optimize PHP code to minimize overhead.

How to use MySQL backup and restore in PHP? How to use MySQL backup and restore in PHP? Jun 03, 2024 pm 12:19 PM

Backing up and restoring a MySQL database in PHP can be achieved by following these steps: Back up the database: Use the mysqldump command to dump the database into a SQL file. Restore database: Use the mysql command to restore the database from SQL files.

How to insert data into a MySQL table using PHP? How to insert data into a MySQL table using PHP? Jun 02, 2024 pm 02:26 PM

How to insert data into MySQL table? Connect to the database: Use mysqli to establish a connection to the database. Prepare the SQL query: Write an INSERT statement to specify the columns and values ​​to be inserted. Execute query: Use the query() method to execute the insertion query. If successful, a confirmation message will be output.

How to fix mysql_native_password not loaded errors on MySQL 8.4 How to fix mysql_native_password not loaded errors on MySQL 8.4 Dec 09, 2024 am 11:42 AM

One of the major changes introduced in MySQL 8.4 (the latest LTS release as of 2024) is that the "MySQL Native Password" plugin is no longer enabled by default. Further, MySQL 9.0 removes this plugin completely. This change affects PHP and other app

How to use MySQL stored procedures in PHP? How to use MySQL stored procedures in PHP? Jun 02, 2024 pm 02:13 PM

To use MySQL stored procedures in PHP: Use PDO or the MySQLi extension to connect to a MySQL database. Prepare the statement to call the stored procedure. Execute the stored procedure. Process the result set (if the stored procedure returns results). Close the database connection.

How to create a MySQL table using PHP? How to create a MySQL table using PHP? Jun 04, 2024 pm 01:57 PM

Creating a MySQL table using PHP requires the following steps: Connect to the database. Create the database if it does not exist. Select a database. Create table. Execute the query. Close the connection.

The difference between oracle database and mysql The difference between oracle database and mysql May 10, 2024 am 01:54 AM

Oracle database and MySQL are both databases based on the relational model, but Oracle is superior in terms of compatibility, scalability, data types and security; while MySQL focuses on speed and flexibility and is more suitable for small to medium-sized data sets. . ① Oracle provides a wide range of data types, ② provides advanced security features, ③ is suitable for enterprise-level applications; ① MySQL supports NoSQL data types, ② has fewer security measures, and ③ is suitable for small to medium-sized applications.

See all articles