本文意在基於Docker-compose部署微服務,不會聊Docker和SpringCloud實現細節,因此讀本文前你要對Docker和SpringCloud有一個基礎的認識。java
nacos
阿里開源的服務發現fp-gateway
網關服務fp-api
api服務fp-user
用戶服務經過簡單的架構圖能夠了解到,
fp-gateway
、fp-api
、fp-user
是咱們基於SpringCloud
構建的應用,並將其註冊給nacos
。nacos
咱們直接使用官方的鏡像便可,剩下這三個應用需編寫鏡像。git
FROM java:8
# 將運行腳本加入到容器中
COPY startup.sh /shell/startup.sh
# 賦予運行權限
RUN chmod +x /shell/startup.sh
# 指定容器時區:東八區
ENV TZ=Asia/Shanghai
RUN ln -snf /usr/share/zoneinfo/$TZ /etc/localtime && echo $TZ > /etc/timezone
# 建立jar包目錄
RUN mkdir jar
# 掛載 jar目錄
VOLUME ["/jar"]
# 進行運行腳本
CMD [ "sh","/shell/startup.sh" ]
複製代碼
#!/bin/bash
# 三個服務鏡像時,只需改這個值gateway->api/user
server_name="fp-gateway"
kill -s 9 `ps -aux | grep $server_name | awk '{print $2}'`
# 切換到jar目錄啓動,目的配置外置
cd /jar
# 啓動
java -jar -Duser.timezone=GMT+08 -XX:+HeapDumpOnOutOfMemoryError -Xms512m -Xmx512m $server_name.jar
複製代碼
docker build -t fp-api:v1 ./fp-api/
docker build -t fp-gateway:v1 ./fp-gateway/
docker build -t fp-user:v1 ./fp-user/
複製代碼
# 執行docker images 出現以下圖狀況,說明鏡像構建成功
docker images
複製代碼
curl -L "https://github.com/docker/compose/releases/download/1.24.0/docker-compose-$(uname -s)-$(uname -m)" -o /usr/local/bin/docker-compose
chmod +x /usr/local/bin/docker-compose
複製代碼
docker-compose -version
複製代碼
version: "3.5"
services:
fp-api:
image: fp-api:v1
container_name: fp-api
volumes:
- /docker/fp/services/fp-api:/jar
ports:
- "10001:10001"
depends_on:
- fp-gateway
fp-user:
image: fp-user:v1
container_name: fp-user
volumes:
- /docker/fp/services/fp-user:/jar
ports:
- "10002:10002"
depends_on:
- fp-gateway
fp-gateway:
image: fp-gateway:v1
container_name: fp-gateway
volumes:
- /docker/fp/services/fp-gateway:/jar
ports:
- "10003:10003"
複製代碼
nacos
這一塊每一個team選擇的服務發現是不同的,這一塊很靈活,因此略過它的部署過程。github
fp/
├── builds
│ ├── fp-api
│ │ ├── Dockerfile
│ │ └── startup.sh
│ ├── fp-gateway
│ │ ├── Dockerfile
│ │ └── startup.sh
│ └── fp-user
│ ├── Dockerfile
│ └── startup.sh
├── services
│ ├── fp-api
│ │ ├── config
│ │ │ └── application.yml
│ │ └── fp-api.jar
│ ├── fp-gateway
│ │ ├── config
│ │ │ └── application.yml
│ │ └── fp-gateway.jar
│ └── fp-user
│ ├── config
│ │ └── application.yml
│ └── fp-user.jar
└── yaml
└── standalone.yml
複製代碼
docker-compose -f ./yaml/standalone.yml up -d
複製代碼
docker ps
複製代碼
在
fp-api
服務調用fp-user
服務個接口。docker
@RestController
public class UserController {
@GetMapping("user")
public String user() {
return "welcome to user app.";
}
}
複製代碼
@FeignClient(value = "footprint-user")
public interface UserFeign {
@GetMapping("user")
public String user();
}
複製代碼
@RestController
public class ApiController {
@Autowired
private UserFeign userFeign;
@GetMapping("test")
public String test() {
return userFeign.user();
}
}
複製代碼
curl http://192.168.0.4:10003/fp/api/test
複製代碼