Implementation approach
Dockerfile
+docker-compose
To build the Docker containertravis-ci
+github
To hookrepo
The change oftravis-ci
callDockerfile
packagingdocker image
And push todockerhub
travis-ci
Log in to the target machine over SSH and copydocker-compose
And execute to complete the deployment
Docker container build
Since the project is built based on Java + Gradle, dockerfile requires a multi-stage build
Build the fat-jar first:
Build a build environment based on Gradle
FROM Gradle: 5.2.1 - jdk8 - alpine AS build-env
# copy the source code
ADD --chown=gradle . /app
WORKDIR /app
Run Gradle Task to build
RUN gradle assemble --info
Copy the code
Copy jar package to jre:
FROM openjdk:8-jre
# time zone
RUN ln -sf /usr/share/zoneinfo/Asia/Shanghai /etc/localtime \
&& echo Asia/Shanghai > /etc/timezone \ && dpkg-reconfigure -f noninteractive tzdata # port EXPOSE 9000 #copy COPY --from=build-env Run CMD [" Java ", "-jar", "/app/bin/xxx.jar"]Copy the code
If you want to ADD a jar, you need to grant permission. Otherwise, the gradle command cannot execute. If you want to ADD a jar, you need to declare the jar from the previous stage.
docker-compose.yaml
version: '2'
services:
xxx-service:
image: xxx:latest
container_name: xxx
environment:
- JAVA_TOOL_OPTIONS=-Xms128m -Xmx256m
ports:
- "9000:8080"
Copy the code
.travis.yaml
language: bash
services:
- docker
sudo: required
branches:
only:
- master
script:
- docker build . -t "xxx:latest"
- docker-compose -f docker-compose.yaml down
- docker-compose -f docker-compose.yaml up -d --force-recreate
- docker-compose -f docker-compose.yaml down
after_success:
- docker login --username=username -p="password" dockerhub
- docker push dockerhub:latest
- chmod 600 id_rsa
- scp -o "StrictHostKeyChecking no" -i id_rsa docker-compose.yml ubuntu@ip:/home/ubuntu/docker/
- ssh -o "StrictHostKeyChecking no" -i id_rsa ubuntu@ip "cd /home/ubuntu/docker/; sudo docker-compose -f docker-compose.yml pull; sudo docker-compose -f docker-compose.yml up -d; exit"
Copy the code
Break it down:
- Statement language: bash
- Services Select the Docker environment
- Script Starts the Docker Image build
- After after_success builds, log in to dockerhub,push image, log in to server and cp docker-compose.
- The command followed by SSH is executed after successful login
Sensitive information can be set by using Travis CI’s environment variable to avoid disclosure of the repository. Ssh_key can be used by Travis CI’s encryption key to avoid disclosure