Deploy Application to Remote Docker Server (Without Kubernetes Cluster) with Gitlab CI/CD

This Tutorial Covers:

Fadhil Rasendriya Prabowo
2 min readMar 20, 2022

This Tutorial Covers:

  1. Run application in docker container in remote server that has Docker.
  2. Run application with configuration (environment variable, secrets, etc) from Gitlab CI/CD pipeline.

Prerequisites

  1. Docker installed in remote machine with ssh access.
  2. Docker credential key stored in CI/CD variable.
  3. SSH private key to remote machine stored in CI/CD variable.

In order for docker client to deploy to specific host, you need to set up environment variable called DOCKER_HOST before executing docker command. DOCKER_HOST value is ssh://usernane@host reference.

Set Up Application Environment And Secrets

Put all your environment variables for your application in gitlab ci/cd variables as file.

example:

.gitlab-ci.yml

Add ssh key to ssh agent:

reference

- chmod 400 $SSH_PRIVATE_KEY
- which ssh-agent || ( apk --update add openssh-client )
- eval $(ssh-agent -s)
- ssh-add $SSH_PRIVATE_KEY
- mkdir -p ~/.ssh
- chmod 700 ~/.ssh
- cat $SSH_KNOWN_HOSTS >> ~/.ssh/known_hosts
- chmod 644 ~/.ssh/known_hosts

Login to docker (If image is private)

- docker login -u _json_key --password-stdin https://$IMAGE_REGISTRY < $JSON_DOCKER_KEY

Run docker command

- docker stop <container-name> || true # stop running container
- docker rm <container-name> || true # delete container
- docker run -p 127.0.0.1:8080:80 --env-file $STG_ENV --name <container-name> -d $IMAGE_REGISTRY/$IMAGE_TAG:stg-$CI_PIPELINE_IID

Example full yml.

DeployStaging:
stage: DeployStaging
image: docker:latest
before_script:
- chmod 400 $SSH_PRIVATE_KEY
- which ssh-agent || ( apk --update add openssh-client )
- eval $(ssh-agent -s)
- ssh-add $SSH_PRIVATE_KEY
- mkdir -p ~/.ssh
- chmod 700 ~/.ssh
- cat $SSH_KNOWN_HOSTS >> ~/.ssh/known_hosts
- chmod 644 ~/.ssh/known_hosts
- docker login -u _json_key --password-stdin https://$IMAGE_REGISTRY < $JSON_DOCKER_KEY
script:
- cat ~/.ssh/known_hosts
- docker stop <container-name> || true
- docker rm <container-name>|| true
- docker run -p 127.0.0.1:8080:80 --env-file $STG_ENV --name <container-name> -d $IMAGE_REGISTRY/$IMAGE_TAG:stg-$CI_PIPELINE_IID
variables:
DOCKER_HOST: ssh://gitlab@$STG_HOST
only:
variables:
- ($CI_COMMIT_BRANCH == "develop")

Now you can check if the application is running.

--

--