准備Dockerfile
FROM java:8 #基於jdk8的環境
COPY *.jar /app.jar #拷貝所有的jar包到/app.jar目錄下
CMD ["--server.port=8080"] # 指定服務器端口
EXPOSE 8080 # 暴露8080端口
ENTRYPOINT ["java", "-jar", "/app.jar"] # 啟動jar包
准備docker-compose.yml
version: '2.6' # 指定版本,這個版本是docker和docker-compose對應的版本
services:
customapp:
build: . # 構建當前目錄下的項目
image: customapp # 鏡像
ports:
- "8080:8080" # 端口
depends_on:
- redis # 依賴redis鏡像
redis:
image: 'redis:alpine' # redis鏡像,精簡版
然后搭建基於Springboot的微服務
pom.xml文件如下
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
</dependencies>
其中pom.xml文件中只引用了較少的依賴,包括redis和starter-web。用於搭建springboot項目
application.properties其中內容
server.port=8080 # 暴露端口
# 為何這里指定redis的服務器時,使用的是“redis”,而不是類似於“localhost”那種服務器的信息。
# 是因為部署在docker容器里面時,直接是引用的redis鏡像。
spring.redis.host=redis # 指定redis的服務器
一個簡單的計數訪問頁面controller
package com.example.composedemo.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.Resource;
/**
* @Author: Xiong Feng
* @Date: 2020/8/4 8:53
* @Description:
*/
@RestController
public class HelloController {
@Resource
private StringRedisTemplate stringRedisTemplate;
@GetMapping("/hello")
public String Hello(){
Long views = stringRedisTemplate.opsForValue().increment("views");
return "Hello Docker Compose, you have views:"+views;
}
}
這個Controller里面就簡單引用了redis,並使用redis的緩存實現計數+1
上面准備步驟做好之后,把springboot項目打包成一個jar包,將Dockerfile文件和docker-compose.yml文件,一起放入linux環境下的同一個目錄
然后再控制台執行命令
docker-compose up --build