一、创建sprigboot项目

springboot项目配置

1.项目正常配置写一个controller获取db数据

@RestController
public class Hello {
    @Autowired
    private JdbcTemplate jdbcTemplate;

    @RequestMapping("/hi")
    public String hello(){
        String sql = "SELECT * FROM person";
        Map<String, Object> stringObjectMap = jdbcTemplate.queryForMap(sql);
        return "docker hello world!"+ JSON.toJSONString(stringObjectMap);
    }
}

2.配置application.yml

# mysqldbserver 对应的是docker-compose.yml中配置的container_name
sprig:
  datasource:
    driver-class-name: com.mysql.jdbc.Driver
    url: jdbc:mysql://mysqldbserver:3306/sys?useUnicode=true&characterEncoding=utf-8&useSSL=false
    username: root
    password: 123456

3.  springboot 的Dockerfile1

FROM java:8
  
VOLUME /vol/development
 
RUN mkdir -p /vol/development
 
WORKDIR /vol/development
 
COPY 你打的jar包.jar /vol/development/app.jar
 
CMD ["java", "-Xmx200m", "-Djava.security.egd=file:/dev/./urandom","-jar","/vol/development/app.jar"]

4.mysql的Dockerfile

FROM mysql:5.7.17

5.docker-compose.yml

version : '3'
services:
  mysqldbserver:
    container_name: mysqldbserver
    image: mysql:5.7.17 
    build:
      context: .
      dockerfile: Dockerfile
    ports:
      - "3306:3306"
    command: [
          'mysqld',
          '--innodb-buffer-pool-size=20M',
          '--character-set-server=utf8',
          '--collation-server=utf8_general_ci',
          '--default-time-zone=+8:00',
          '--lower-case-table-names=1'
        ]
    environment:
      MYSQL_DATABASE: sys
      MYSQL_ROOT_PASSWORD: 123456
  springappserver:
    container_name: springappserver
    build:
      context: .
      dockerfile: Dockerfile1
    ports:
      - "8080:8080"
    volumes:
      - /vol/development
    depends_on:
      - mysqldbserver
    links:
      - mysqldbserver

测试

1.以上文件以及打的jar放一个目录

2.在目录路径命令 docker-compose up启动

3.连接容器ip的数据库,sys数据库下新建person表写入数据。

3.浏览器 `https:容器ip:8080/hi` 访问查询数据

Logo

权威|前沿|技术|干货|国内首个API全生命周期开发者社区

更多推荐