search
HomeDatabaseMysql TutorialHow to use dockercompose to build nginx+mysql+redis+springboot project

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

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

C.Dockerfile

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

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;
        }
    }
}

- /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

- /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

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

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

Stop

docker-compose down

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
This article is reproduced at:亿速云. If there is any infringement, please contact admin@php.cn delete
MySQL: BLOB and other no-sql storage, what are the differences?MySQL: BLOB and other no-sql storage, what are the differences?May 13, 2025 am 12:14 AM

MySQL'sBLOBissuitableforstoringbinarydatawithinarelationaldatabase,whileNoSQLoptionslikeMongoDB,Redis,andCassandraofferflexible,scalablesolutionsforunstructureddata.BLOBissimplerbutcanslowdownperformancewithlargedata;NoSQLprovidesbetterscalabilityand

MySQL Add User: Syntax, Options, and Security Best PracticesMySQL Add User: Syntax, Options, and Security Best PracticesMay 13, 2025 am 12:12 AM

ToaddauserinMySQL,use:CREATEUSER'username'@'host'IDENTIFIEDBY'password';Here'showtodoitsecurely:1)Choosethehostcarefullytocontrolaccess.2)SetresourcelimitswithoptionslikeMAX_QUERIES_PER_HOUR.3)Usestrong,uniquepasswords.4)EnforceSSL/TLSconnectionswith

MySQL: How to avoid String Data Types common mistakes?MySQL: How to avoid String Data Types common mistakes?May 13, 2025 am 12:09 AM

ToavoidcommonmistakeswithstringdatatypesinMySQL,understandstringtypenuances,choosetherighttype,andmanageencodingandcollationsettingseffectively.1)UseCHARforfixed-lengthstrings,VARCHARforvariable-length,andTEXT/BLOBforlargerdata.2)Setcorrectcharacters

MySQL: String Data Types and ENUMs?MySQL: String Data Types and ENUMs?May 13, 2025 am 12:05 AM

MySQloffersechar, Varchar, text, Anddenumforstringdata.usecharforfixed-Lengthstrings, VarcharerForvariable-Length, text forlarger text, AndenumforenforcingdataAntegritywithaetofvalues.

MySQL BLOB: how to optimize BLOBs requestsMySQL BLOB: how to optimize BLOBs requestsMay 13, 2025 am 12:03 AM

Optimizing MySQLBLOB requests can be done through the following strategies: 1. Reduce the frequency of BLOB query, use independent requests or delay loading; 2. Select the appropriate BLOB type (such as TINYBLOB); 3. Separate the BLOB data into separate tables; 4. Compress the BLOB data at the application layer; 5. Index the BLOB metadata. These methods can effectively improve performance by combining monitoring, caching and data sharding in actual applications.

Adding Users to MySQL: The Complete TutorialAdding Users to MySQL: The Complete TutorialMay 12, 2025 am 12:14 AM

Mastering the method of adding MySQL users is crucial for database administrators and developers because it ensures the security and access control of the database. 1) Create a new user using the CREATEUSER command, 2) Assign permissions through the GRANT command, 3) Use FLUSHPRIVILEGES to ensure permissions take effect, 4) Regularly audit and clean user accounts to maintain performance and security.

Mastering MySQL String Data Types: VARCHAR vs. TEXT vs. CHARMastering MySQL String Data Types: VARCHAR vs. TEXT vs. CHARMay 12, 2025 am 12:12 AM

ChooseCHARforfixed-lengthdata,VARCHARforvariable-lengthdata,andTEXTforlargetextfields.1)CHARisefficientforconsistent-lengthdatalikecodes.2)VARCHARsuitsvariable-lengthdatalikenames,balancingflexibilityandperformance.3)TEXTisidealforlargetextslikeartic

MySQL: String Data Types and Indexing: Best PracticesMySQL: String Data Types and Indexing: Best PracticesMay 12, 2025 am 12:11 AM

Best practices for handling string data types and indexes in MySQL include: 1) Selecting the appropriate string type, such as CHAR for fixed length, VARCHAR for variable length, and TEXT for large text; 2) Be cautious in indexing, avoid over-indexing, and create indexes for common queries; 3) Use prefix indexes and full-text indexes to optimize long string searches; 4) Regularly monitor and optimize indexes to keep indexes small and efficient. Through these methods, we can balance read and write performance and improve database efficiency.

See all articles

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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor