一、Docker-compse安装

  1. 下载docker-compose
sudo curl -L "https://github.com/docker/compose/releases/download/1.24.1/docker-compose-$(uname -s)-$(uname -m)" -o /usr/local/bin/docker-compose
  1. 授权
chmod 777 /usr/local/bin/docker-compose
  1. 查看版本
[root@192 ~]# docker-compose version
docker-compose version 1.24.1, build 4667896b
docker-py version: 3.7.3
CPython version: 3.6.8
OpenSSL version: OpenSSL 1.1.0j  20 Nov 2018

二、准备java项目

1. 创建springboot项目

  1. pom文件
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.3.5.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.example</groupId>
    <artifactId>docker_images</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>docker_images</name>
    <description>Demo project for Spring Boot</description>

    <properties>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <!-- swagger -->
        <!-- https://mvnrepository.com/artifact/io.springfox/springfox-swagger-ui -->
        <dependency>
            <groupId>com.github.xiaoymin</groupId>
            <artifactId>swagger-bootstrap-ui</artifactId>
            <version>1.9.6</version>
        </dependency>
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger2</artifactId>
            <version>2.9.2</version>
        </dependency>

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </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>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>
  1. 配置swagger和编写测试接口

## 1. 引入swagger是方便测试
package com.example.docker_images.config;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

/**
 * @author Javacfox
 */
@Configuration
@EnableSwagger2
public class Swagger2Config {

    /**
     * 设置swagger跨域,提供给service调用
     * @return
     */
    @Bean
    public WebMvcConfigurer crossConfigurer(){
        WebMvcConfigurer webMvcConfigurerAdapter = new WebMvcConfigurer() {
            @Override
            public void addCorsMappings(CorsRegistry registry) {
                registry.addMapping("/v2/api-docs");
                registry.addMapping("/**");
            }
        };
        return webMvcConfigurerAdapter;
    }

    @Bean
    public Docket createRestApi(){
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()
                //基础扫描包路径
                .apis(RequestHandlerSelectors.basePackage("com.example.docker_images.controller"))
                .paths(PathSelectors.any())
                .build();
    }

    private ApiInfo apiInfo(){
        return new ApiInfoBuilder()
                .title("java")
                .description("java项目打包成docker images并运行")
                .version("1.0.0")
                .build();
    }

    private CorsConfiguration buildConfig() {
        CorsConfiguration corsConfiguration = new CorsConfiguration();
        // 1允许任何域名使用
        corsConfiguration.addAllowedOrigin("*");
        // 2允许任何头
        corsConfiguration.addAllowedHeader("*");
        // 3允许任何方法(post、get等)
        corsConfiguration.addAllowedMethod("*");
        return corsConfiguration;
    }

    @Bean
    public CorsFilter corsFilter() {
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", buildConfig());
        return new CorsFilter(source);
    }

}

# 2. 接口编写
package com.example.docker_images.controller;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/hello")
public class HelloController {

    @GetMapping("/sayHello")
    public String say(String userName){
        return "hello,"+userName+"!";
    }
}

# 3. 主类
package com.example.docker_images;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class DockerImagesApplication {

    public static void main(String[] args) {
        SpringApplication.run(DockerImagesApplication.class, args);
    }

}

上面是所有的java项目,非常简单,目前只是为了测试。

2. 编写dockerFile、docker-compose.yml文件

  1. dockerFile
# 以jdk8为基础镜像
FROM openjdk:8
# 描述
LABEL description="Java 8"

# 暴露接口
EXPOSE 8088
# 将主机中的jar包添加到镜像中
ADD /docker_images-0.0.1-SNAPSHOT.jar docker_images-0.0.1-SNAPSHOT.jar
# 运行jar包
ENTRYPOINT ["java", "-jar","docker_images-0.0.1-SNAPSHOT.jar"]
  1. docker-compose.yml
version: '3'
services:

  test:
    container_name: java_test #配置容器名
    build:
      context: .
      dockerfile: DockerFile #指定dockerFile文件
    image: java/test:8.0.0 # 指定镜像名
    ports:
          - "8088:8088" # 暴露端口
    volumes:
          - /logs:/logs # 创建容器数据卷

3. 创建并运行镜像

  1. 上传文件到服务器:/root/docker-image
    image
  2. 到服务器命令台

[root@192 ~]# cd /root/docker_image
[root@192 docker_image]# ll
total 26384
-rw-r--r--. 1 root root      217 Nov 15 20:08 docker-compose.yml
-rw-r--r--. 1 root root      188 Nov 15 04:32 DockerFile
-rw-r--r--. 1 root root 27005222 Nov 12 10:27 docker_images-0.0.1-SNAPSHOT.jar
[root@192 docker_image]# docker-compose build
Building test
Step 1/5 : FROM openjdk:8
Trying to pull repository docker.io/library/openjdk ... 
8: Pulling from docker.io/library/openjdk
e4c3d3e4f7b0: Pull complete
101c41d0463b: Pull complete
8275efcd805f: Pull complete
751620502a7a: Pull complete
a59da3a7d0e7: Pull complete
5ad32ac1e527: Pull complete
7ee60316f31a: Pull complete
Digest: sha256:44713efa363430c6d991f59bbc47238838ecf09a2df4dfb8bbbb07a55f8aeeae
Status: Downloaded newer image for docker.io/openjdk:8
 ---> 192ceee8f2fd
Step 2/5 : LABEL description "Java 8"
 ---> Running in 4b14bbeddd1d
 ---> 1b5324a856ad
Removing intermediate container 4b14bbeddd1d
Step 3/5 : EXPOSE 8088
 ---> Running in e08c74d7f0dd
 ---> bb0a7991cb0e
Removing intermediate container e08c74d7f0dd
Step 4/5 : ADD /docker_images-0.0.1-SNAPSHOT.jar docker_images-0.0.1-SNAPSHOT.jar
 ---> 8fa5fc5834ff
Removing intermediate container 32c95ff2d8a0
Step 5/5 : ENTRYPOINT java -jar docker_images-0.0.1-SNAPSHOT.jar
 ---> Running in c40f5144492f
 ---> b7258eff2bc4
Removing intermediate container c40f5144492f
Successfully built b7258eff2bc4
[root@192 docker_image]# docker-compose up -d
Creating java_test ... done
[root@192 docker_image]# docker ps
CONTAINER ID        IMAGE               COMMAND                  CREATED             STATUS              PORTS                    NAMES
61551d9dbee7        java/test:8.0.0     "java -jar docker_..."   7 seconds ago       Up 7 seconds        0.0.0.0:8088->8088/tcp   java_test

步骤解说:

  1. 进入到jar包所在文件目录
  2. 创建镜像:docker-compose build
  3. 运行镜像:docker-compose up -d

三、访问测试

image

Logo

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

更多推荐