Docker-compose部署java项目

liyansring 2020-07-18

Docker-compose部署java项目

前置条件:

  1. 安装docker
  2. 安装docker-compose
  3. 防火墙啥的都设置好

dockerfile-demo

FROM java:8
VOLUME /tmp
WORKDIR /
ADD ./project-demo-1.0.0.jar project-demo.jar
RUN bash -c ‘touch /project-demo.jar‘
EXPOSE 8080
ENTRYPOINT ["java","-jar","/project-demo.jar"]

compose-project-demo.yaml

version: ‘3‘

# 关于网络,如果用到mysql或者redis,并且希望在同一个网络,那么就可以直接使用同一个网络名
# docker network create project-demo_bridge
networks:
  project-demo_bridge:
    driver: bridge

services:
   project-demo:
     container_name: project-demo
     image: project-demo:1.0
     restart: always
     volumes:
       # 同步时间
       - /etc/localtime:/etc/localtime:ro
       # 如果项目有些日志或者写文件,需要同步到宿主机器,也需要定义相应的卷
       - ./data:/etc/project-demo/data
       - ./log:/etc/project-demo/log
     ports:
       - 8080:8080
     networks:
       - project-demo_bridge

start-project-demo.sh

#! /usr/bin/bash
PROJECT_NAME=project-demo
containerName=$PROJECT_NAME:1.0
imagesName=$PROJECT_NAME:1.0

# 定义一个名称变量
network_name="$PROJECT_NAME_bridge"

filterName=`docker network ls | grep $network_name | awk ‘{ print $2 }‘`

if [ "$filterName" == "" ]; then
    # 不存在就创建
    docker network create $network_name
    echo "Created network $network_name success!!"
fi

existContainer=`docker inspect --format ‘{{.State.Running}}‘ ${containerName}`

function delExistImagesAndContainer() {
    if [ "${existContainer}" == "true" ]; then
        docker stop ${containerName}
        echo "容器:${containerName}已停止"
        docker rm ${containerName}
        echo "容器:${containerName}已删除"

        docker rmi ${imagesName}
        echo "镜像:${containerName}已删除"
    fi
}

function buildJar(){
    echo "正在构建jar镜像"
    # 其实这个构建指令是可以直接写到compose的那个启动文件中的
    docker build -f dockerfile-$PROJECT_NAME -t $PROJECT_NAME:1.0 .
    echo "镜像构建完成"
    echo "正在创建并启动容器"
    docker-compose -f ./compose-$PROJECT_NAME.yaml up -d
}

delExistImagesAndContainer

buildJar

相关推荐