通过Docker Compose来实现项目可以指定读取不同环境的yml包
1. 配置文件
version: '3.8'
services:
docker-test:
image: openjdk:8-jdk-alpine
ports:
- "${APP_PORT}:${CONTAINER_PORT}"
volumes:
- "${JAR_PATH}:/app/docker-test.jar"
- "${APPLICATION_YML}:/app/config/application.yml"
- "${APPLICATION_DEV_YML}:/app/config/application-dev.yml"
- "${APPLICATION_PROD_YML}:/app/config/application-prod.yml"
- "${LOGS_PATH}:/app/logs"
environment:
- SPRING_PROFILES_ACTIVE=${SPRING_PROFILES_ACTIVE}
command: >
sh -c "java -jar /app/docker-test.jar > /app/logs/log.out 2>&1"
restart: always
# env文件
# 配置文件路径
CONFIG_PATH=./
# 应用程序配置文件
APPLICATION_YML=${CONFIG_PATH}/application.yml
APPLICATION_DEV_YML=${CONFIG_PATH}/application-dev.yml
APPLICATION_PROD_YML=${CONFIG_PATH}/application-prod.yml
# Spring Profile (可以是 dev、prod 或其他配置)
SPRING_PROFILES_ACTIVE=dev
# 端口映射
APP_PORT=1888
CONTAINER_PORT=9898
JAR_PATH=./docker-test-0.0.1-SNAPSHOT.jar
LOGS_PATH=./logs
2. 启动命令
(base) ➜ docker-project docker-compose up -d
WARN[0000] /Users/fanzhen/Documents/docker-project/docker-compose.yml: the attribute `version` is obsolete, it will be ignored, please remove it to avoid potential confusion
[+] Running 4/4
✔ docker-test Pulled 31.7s
✔ 0362ad1dd800 Pull complete 3.3s
✔ 571218f61883 Pull complete 3.4s
✔ abe576d65b4c Pull complete 20.7s
[+] Running 2/2
✔ Network docker-project_default Created 0.0s
✔ Container docker-project-docker-test-1 Started
(base) ➜ docker-project docker-compose ps
NAME IMAGE COMMAND SERVICE CREATED STATUS PORTS
docker-project-docker-test-1 openjdk:8-jdk-alpine "sh -c 'java -jar /a…" docker-test 8 minutes ago Up 8 minutes 0.0.0.0:1888->8989/tcp
(base) ➜ ~ docker images
REPOSITORY TAG IMAGE ID CREATED SIZE
openjdk 8-jdk-alpine e4105db9d469 5 years ago 103MB
(base) ➜ ~ docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
8ac0558be7c9 openjdk:8-jdk-alpine "sh -c 'java -jar /a…" 11 minutes ago Up 11 minutes 0.0.0.0:1888->8989/tcp docker-project-docker-test-1
查看容器内容
(base) ➜ ~ docker exec -it docker-project-docker-test-1 /bin/sh
/app # pwd
/app
/app # ls
# 宿主机内安装curl
apk add --no-cache curl
/ # curl -L -X GET 'http://0.0.0.0:9898/api/v1/heart-beat' \
>
prod
/ #
切换不同环境
(base) ➜ docker-project docker-compose stop docker-test
[+] Stopping 1/0
✔ Container docker-project-docker-test-1 Stopped 0.1s
(base) ➜ docker-project SPRING_PROFILES_ACTIVE=prod docker-compose up -d docker-test
[+] Running 1/1
✔ Container docker-project-docker-test-1 Started
注意挂载的文件权限要777
# 在容器内检查挂载的文件确保它确实链接到了你期望的宿主机文件:
(base) ➜ docker-project docker exec -it docker-project-docker-test-1 cat /app/config/application-dev.yml
spring:
application:
name: docker-test
server:
port: 9898
address: 0.0.0.0
env: devasdasd