Deploy a Docker image on Rancher with Gitlab CI
October 02, 2017
I recently started working with Docker images that we build through our continuous integration pipe. Gitlab CI is an accessible and easy-to-use tool and we’ll see how to use it to deploy docker images on Rancher. To start, we will need to set up a docker-compose.yml file that describes the services we want to deploy. This may include a web application, a database and any other service we may need (storage, e-mail, cache, proxy, etc.) On the example below, we will have 3 services:
- our web application
- a database service (postgres)
- a storage instance for the database
version: '2' services: app: image: registry.example.com/app:dev environment: DB_HOST: db DB_NAME: app_db DB_PASSWORD: a_p4ssword DB_USER: postgres DB_PORT: 5432 links: - db:db ports: - 4034:4032/tcp command: - foreground labels: io.rancher.container.pull_image: always db-storage: image: busybox volumes: - /var/lib/postgresql/data/pgdata labels: io.rancher.container.start_once: 'true' db: image: postgres environment: PGDATA: /var/lib/postgresql/data/pgdata POSTGRES_DB: app_db POSTGRES_PASSWORD: a_p4ssword POSTGRES_USER: postgres volumes_from: - db-storage ports: - 5436:5432/tcp expose: - "5432" labels: io.rancher.sidekicks: db-storage
You will note that we expose our app on port 4034et the database on port 5436. After that, we set our continious deployment processes in the .gitlab-ci.yml file. We will use the tagip/rancher-cli which contains an installed Rancher CLI, the command-line tools for Rancher.
deploy_app: stage: deploy image: tagip/rancher-cli script: - rancher --debug up -d --stack "our-app" - rancher --debug up -d --force-upgrade --pull --stack "our-app" --confirm-upgrade app
The first line in script will check that a stack call “our-app” is up in Rancher, if not, it will first create it. The second command downloads (with option --pull ) the latest image built for app et update the stack (--confirm-upgrade ). Finally, we need to get Rancher credentials so the previous rancher command can connect to the correct instance. We get them from Rancher in Rancher > API > Keys We will put these informations in Gitlab and they will be passed as environment variable on each CI pipeline. We set them in Gitlab at _Settings > Pipelines > Secret variables _
- RANCHER_ACCESS_KEY: the generated access key
- RANCHER_SECRET_KEY: secret key associated
- RANCHER_URL: the URL of Rancher
Et voila, our Rancher stack is now updated through Gitlab CI.