add doc
This commit is contained in:
parent
b97c8869af
commit
1354597863
91
docs/guides/spring-boot-docker.md
Normal file
91
docs/guides/spring-boot-docker.md
Normal file
@ -0,0 +1,91 @@
|
||||
在Spring Boot 3中部署使用Gradle构建的应用到Docker的教程如下,并在Docker Compose部分增加MySQL服务:
|
||||
|
||||
### 1. 添加Docker支持
|
||||
|
||||
创建一个名为`Dockerfile`的文件在项目根目录下,内容为:
|
||||
|
||||
```Dockerfile
|
||||
# 使用官方的Java运行时作为父镜像
|
||||
FROM gradle:8.0.0-jdk17 AS build
|
||||
WORKDIR /app
|
||||
|
||||
# 将Gradle的配置文件复制到镜像中
|
||||
COPY gradlew .
|
||||
COPY gradle gradle
|
||||
COPY build.gradle .
|
||||
COPY settings.gradle .
|
||||
|
||||
COPY src src
|
||||
# 构建应用
|
||||
RUN gradle bootJar
|
||||
|
||||
# 使用官方的Java运行时作为最终的运行环境
|
||||
FROM openjdk:17-jdk-slim
|
||||
WORKDIR /app
|
||||
COPY --from=build /app/build/libs/*.jar app.jar
|
||||
|
||||
# 设置应用运行的端口
|
||||
EXPOSE 8080
|
||||
|
||||
# 启动应用
|
||||
ENTRYPOINT ["java","-jar","/app/app.jar"]
|
||||
```
|
||||
|
||||
注意:请确保`ENTRYPOINT`中的`app.jar`与实际构建出的jar文件名匹配,通常使用`bootJar`任务生成的jar会带有版本信息。
|
||||
|
||||
### 2. 构建Docker镜像
|
||||
|
||||
在包含Dockerfile的项目根目录下,执行以下命令构建Docker镜像:
|
||||
|
||||
```bash
|
||||
docker build -t my-spring-boot-app:3.0 .
|
||||
```
|
||||
|
||||
### 3. 运行Docker容器
|
||||
|
||||
构建完成后,启动容器:
|
||||
|
||||
```bash
|
||||
docker run -p 8080:8080 -t my-spring-boot-app:3.0
|
||||
```
|
||||
|
||||
|
||||
### 4. 使用Docker Compose
|
||||
|
||||
创建一个`docker-compose.yml`文件,配置应用服务和MySQL服务:
|
||||
|
||||
```yaml
|
||||
version: '3.8'
|
||||
|
||||
services:
|
||||
db:
|
||||
image: mysql:8.0.30
|
||||
restart: always
|
||||
environment:
|
||||
MYSQL_ROOT_PASSWORD: example
|
||||
MYSQL_DATABASE: mydb
|
||||
MYSQL_USER: myuser
|
||||
MYSQL_PASSWORD: mypassword
|
||||
volumes:
|
||||
- dbdata:/var/lib/mysql
|
||||
|
||||
app:
|
||||
build: .
|
||||
ports:
|
||||
- "8080:8080"
|
||||
depends_on:
|
||||
- db
|
||||
|
||||
volumes:
|
||||
dbdata:
|
||||
```
|
||||
|
||||
这个`docker-compose.yml`文件定义了一个MySQL服务(`db`)和你的Spring Boot应用服务(`app`),并且应用服务依赖于数据库服务。记得根据你的需求调整数据库的环境变量。
|
||||
|
||||
现在,你可以使用Docker Compose来启动整个服务栈:
|
||||
|
||||
```bash
|
||||
docker-compose up -d
|
||||
```
|
||||
|
||||
这将会创建并启动应用和数据库的容器,`-d`参数表示以后台方式运行服务。
|
Loading…
Reference in New Issue
Block a user