GitLab Pipeline
Deploy to Docker

CI/CD

Docker

SSH

SRE | Hetzner Load balancing Nginx, Keepalived

GitLab Deploy to Docker

Intro

This is example GitLab Pipeline used to deploy NodeJS app into private Docker production environment.

Static website will be packaged into Nginx container that will serve the content. It will use standard tcp port 80 to accept client connections. We will deploy the newly created container with the updated website content in the remote server and configure it to accept connections on the port 3210 (it will be mapped to the containers port 80).

SSH Config

We need to take the SSH key from the remote server and add it into CICD variable in Gitlab. We must take private key from the remote server. It is usually located in:

    
    /home/<user>/.ssh/id_rsa

    or
    
    /home/<user>/.ssh/id_ed25519 
                

Content of this file should be copied into the CICD variable, ie. SSH_KEY:


    Settings -> CI/CD -> Variables

    Type: Variable
    Value: Paste the content from id_rsa file and add new line at the end    
    
                

Docker Registry

We will create Access Token to communicate with the Registry and allow this token only to pull images from the Registry.

    
    Settings -> Access Tokens

    role: Reporter
    scope: read_registry
                

Pipeline Explained

                    
    image: docker:20.10.10

    stages:
    - CI 
    - Deploy 

    build new Docker:
    services:
        - docker:20.10.10-dind
    stage: CI
    script:
        - echo "Build new Docker image with latest content"
        - docker login -u $CI_REGISTRY_USER -p $CI_REGISTRY_PASSWORD $CI_REGISTRY
        - docker build -t $CI_REGISTRY_IMAGE/my-site .
        - docker push $CI_REGISTRY_IMAGE/my-site
    only:
        changes:
        - index.html

    deploy to production:
    stage: Deploy
    before_script:
        # Inject SSH key of the remote deployment server inside the container
        - 'command -v ssh-agent > /dev/null || (apk add --update openssh-client)'
        - eval $(ssh-agent -s)
        - echo "$SSH_KEY_PROSOLVER" | tr -d '\r' | ssh-add -
        - mkdir -p ~/.ssh
        - chmod 700 ~/.ssh
        - ssh-keyscan $PROSOLVER_HOST >> ~/.ssh/known_hosts
        - chmod 644 ~/.ssh/known_hosts 
    script:
        - echo "Docker login to the Docker Registry of the Gitlab Repository"
        - ssh $SSH_USER_PROSOLVER@$PROSOLVER_HOST "docker login -u $CI_REGISTRY_USER -p $CI_REGISTRY_PASSWORD $CI_REGISTRY"
        # Deploy - run the container in the remote server and map the ports
        - ssh $SSH_USER_PROSOLVER@$PROSOLVER_HOST "docker pull $CI_REGISTRY_IMAGE/my-site"
        - ssh $SSH_USER_PROSOLVER@$PROSOLVER_HOST "docker run -d -p 3210:80 $CI_REGISTRY_IMAGE/my-site"
    when: manual