I have flask application, code version control in the own instance Gitlab, application run in the docker container. I was set up full automated pipeline in the Gitlab-CI that on every push – build a new version of the application image, push it into GitLab image registry and connect to the remote docker server and update running container with new image version.
So – code, commit, push – everything goest in auto mode.
This is my gitlab-ci.yml
image: docker:18.09.7 services: - docker:18.09.7-dind stages: - build - deploy before_script: - docker login -u gitlab-ci-token -p $CI_JOB_TOKEN $CI_REGISTRY build: only: - pushes stage: build script: - docker build -t $CI_REGISTRY_IMAGE:$CI_COMMIT_SHORT_SHA -t $CI_REGISTRY_IMAGE:latest . - docker push $CI_REGISTRY_IMAGE:$CI_COMMIT_SHORT_SHA - docker push $CI_REGISTRY_IMAGE:latest deploy: only: - pushes stage: deploy before_script: - docker login -u gitlab-ci-token -p $CI_JOB_TOKEN $CI_REGISTRY - cp $DOCKER_CACERT ~/.docker/ca.pem && cp $DOCKER_CERT ~/.docker/cert.pem && cp $DOCKER_KEY ~/.docker/key.pem - export DOCKER_HOST=tcp://MYSERVER.COM:2376 DOCKER_TLS_VERIFY=1 - docker stop $CI_PROJECT_NAME || true - docker rm $CI_PROJECT_NAME || true - docker rmi $CI_REGISTRY_IMAGE:latest - docker pull $CI_REGISTRY_IMAGE:latest script: - docker run --name $CI_PROJECT_NAME -d -p 127.0.0.1:5000:5000 --restart unless-stopped -e DATABASE_URL="$DATABASE_URL" -e SECRET_KEY=$SECRET_KEY -e GOOGLE_OAUTH_CLIENT_ID=$GOOGLE_OAUTH_CLIENT_ID -e GOOGLE_OAUTH_CLIENT_SECRET=$GOOGLE_OAUTH_CLIENT_SECRET -e SENTRY_ENV=$SENTRY_ENV -e SENTRY_DSN="$SENTRY_DSN" $CI_REGISTRY_IMAGE:latest
Some explanations.
- In before_script authorize in the local image registry
- only: pushes (build and deploy only on push action, because if you push 10 commits it’s trigger 10 build processes)
- In deploy->before_script again authorize, but on remote production server using certificates that must be added to the project variables (GitLab Project -> Settings -> CI/CD -> Variables) type: file, 3 vars: $DOCKER_CACERT (contents ca.pem), $DOCKER_CERT (contents client.pem), $DOCKER_KEY (contents cclient.key)). How to enable and generate remote docker certificates.
- Ofc change “DOCKER_HOST=tcp://MYSERVER.COM:2376” to your’s docker server IP or domain and correct API port.
- In script goes start container using just updated image in the registry, change and remove unnecessary environment variables.