docker-compose 構建 Springboot 項目

docker-compose 構建 Springboot 項目

Springboot項目

配置信息

spring.datasource.url=jdbc:mysql://localhost:3306/test
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.jpa.properties.hibernate.hbm2ddl.auto=update
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL5InnoDBDialect
spring.jpa.show-sql=true

主要功能

計算客戶端訪問次數

@RestController
public class VisitorController {

    @Autowired
    private VisitorRepository repository;
	
    @RequestMapping("/")
    public String index(HttpServletRequest request) {
        String ip=request.getRemoteAddr();
        Visitor visitor=repository.findByIp(ip);
        if(visitor==null){
            visitor=new Visitor();
            visitor.setIp(ip);
            visitor.setTimes(1);
        }else {
            visitor.setTimes(visitor.getTimes()+1);
        }
        repository.save(visitor);
        return "我的IP "+visitor.getIp()+" 已經被訪問了"+visitor.getTimes()+" 次了.";
    }
}

Dockerfile

FROM maven:3.5-jdk-8
COPY ./settings.xml /usr/share/maven/ref/

使用 maven 進行構建Springboot項目,因爲構建過程中默認是從外網下載 jar 包,所以根據 官網說明,將自定義國內源鏡像 setting.xml 文件放在 Dockerfile 所在目錄並在 Dockerfile 內容加上 COPY ./settings.xml /usr/share/maven/ref/ 即可。

settings.xml 配置參考阿里巴巴開源鏡像站

Mysql

使用 mysql/mysql-server:5.7

Web容器(Nginx)

使用 nginx:1.13

配置信息

server {
    listen 80;
    charset utf-8;
    access_log off;

    location / {
        proxy_pass http://app:8080;
        proxy_set_header Host $host:$server_port;
        proxy_set_header X-Forwarded-Host $server_name;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    }

    location /static {
        access_log   off;
        expires      30d;

        alias /app/static;
    }
}

在一組 compose 的服務通訊需要使用 services 的名稱進行訪問

docker-compose.yml

version: '3'
services:
  nginx:
   container_name: v-nginx
   image: nginx:1.13
   restart: always
   ports:
   - 80:80
   - 443:443
   volumes:
   - ./nginx/conf.d:/etc/nginx/conf.d
    
  mysql:
   container_name: v-mysql
   image: mysql/mysql-server:5.7
   environment:
    MYSQL_DATABASE: test
    MYSQL_ROOT_PASSWORD: root
    MYSQL_ROOT_HOST: '%'
   ports:
   - "3306:3306"
   restart: always
    
  app:
    restart: always
    build: ./app
    working_dir: /app
    volumes:
      - ./app:/app
      - ~/.m2:/root/.m2
    expose:
      - "8080"
    depends_on:
      - nginx
      - mysql
    command: mvn clean spring-boot:run -Dspring-boot.run.profiles=docker
  • ports: 使用主機端口映射容器端口
  • expose: 暴露端口
  • restart: always 表示如果服務啓動不成功會一直嘗試(重要)
  • volumes: 加載本地目錄下的配置文件到容器目標地址下

啓動/關閉服務與測試

啓動服務

docker-compose up -d

測試

打開網頁 http://ip_addr
訪問測試即可

關閉服務

docker-compose down

參考

https://github.com/ityouknow/spring-boot-examples
http://www.ityouknow.com/springboot/2018/03/28/dockercompose-springboot-mysql-nginx.html

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章