Ruan Bekker's Blog

From a Curious mind to Posts on Github

Setup a 3 Node Docker Swarm Cluster on Ubuntu 16.04

Docker Swarm is a Clustering and Orchestration Framework for the Docker ecosystem. Have a look at their official documentation for detailed information.

In this Tutorial we will Setup a 3 Node Docker Swarm Cluster and to Demonstrate How Easy it is to Deploy a Web Application with 2 Replicas from a Docker Image.



Overview of What we will be Doing

  • Install Docker on 3 Servers with Ubuntu 16.04
  • Initialize the Swarm and Join the Worker Nodes
  • Create a Nginx Service with 2 Replicas
  • Do some Inspection: View some info on the Service

Prerequisites

3 Fresh Deployed Ubuntu 16.04 Servers. ( 1GB Memory Servers will be good for development )

What is Docker

Docker is a Open Source Technology that allows you to create lightweight, isolated, reproducible application instances which is called Containers. Docker is built on top of the LXC technology, so it uses Linux Containers and as mentioned, it’s lightweight compared to a traditional VM.

A Container is isolated and uses the Kernel of the Docker host, it also utilizes Kernel features such as cgroups and namespaces in order to make them isolated.

Installing Docker Community Edition

Remove any older versions of Docker that might be present and install the dependencies:

1
2
3
$ sudo apt remove docker docker-engine -y
$ sudo apt install linux-image-extra-$(uname -r) linux-image-extra-virtual python-setuptools -y
$ sudo apt install apt-transport-https ca-certificates curl software-properties-common -y

Get the needed repository to setup Docker Community Edition:

1
2
3
$ curl -fsSL https://download.docker.com/linux/ubuntu/gpg | sudo apt-key add -
$ sudo apt-key fingerprint 0EBFCD88
$ sudo add-apt-repository "deb [arch=amd64] https://download.docker.com/linux/ubuntu $(lsb_release -cs) stable"

Update the repository index and Install Docker Community Edition:

1
2
3
4
$ sudo apt update
$ sudo apt install docker-ce -y
$ sudo easy_install pip
$ sudo pip install docker-compose

Enable Docker on Startup and Start the Docker Engine:

1
2
$ sudo systemctl enable docker
$ sudo systemctl restart docker

If you would like to execute your docker commands without sudo, add your user to the docker group:

1
$ sudo usermod -aG docker $(whoami)

Test your Setup by Running a Hello World Container. You will see that if the image is not in the local docker image cache, it will pull the image from docker hub (or the respective docker registry), then once the image is saved locally, docker will then instantiate the container from that image:

1
2
3
4
5
6
7
8
9
$ docker run hello-world
Unable to find image 'hello-world:latest' locally
latest: Pulling from library/hello-world
78445dd45222: Pull complete
Digest: sha256:c5515758d4c5e1e838e9cd307f6c6a0d620b5e07e6f927b07d05f6d12a1ac8d7
Status: Downloaded newer image for hello-world:latest

Hello from Docker!
This message shows that your installation appears to be working correctly.

DNS Configuration

If you have a DNS Server you can configure the A Records for these hosts on DNS, but for simplicity, I will add the noted IP Addresses from the previous step into my /etc/hosts file so we can resolve names to IP’s

Open up the the hosts file:

1
$ sudo vim /etc/hosts

In my example, my IP Addresses:

1
2
3
192.0.2.41  manager
192.0.2.42  worker-1
192.0.2.43  worker-2

Repeat the above steps on the other 2 Servers and make note of the IP Addresses of each node. You should be able to ping and reach the nodes that was configured. Make sure to allow all traffic between these nodes.

Initialize the Swarm:

Now we will initialize the swarm on the manager node and as we have more than one network interface, we will specify the –advertise-addr option:

1
2
3
4
5
6
7
8
9
10
$ docker swarm init --advertise-addr 192.0.2.41
Swarm initialized: current node (siqyf3yricsvjkzvej00a9b8h) is now a manager.

    To add a worker to this swarm, run the following command:

    docker swarm join \
    --token SWMTKN-1-0eith07xkcg93lzftuhjmxaxwfa6mbkjsmjzb3d3sx9cobc2zp-97s6xzdt27y2gk3kpm0cgo6y2 \
    192.0.2.41:2377

    To add a manager to this swarm, run 'docker swarm join-token manager' and follow the instructions.

From the response above, we received the join token that allows the workers to register with the manager node. If its a scenario where you want to have more than one manager node, you can run docker swarm join-token manager to receive the join token for additional manager.

Let’s add the two worker nodes to the manager:

1
2
$ [worker-1] docker swarm join --token SWMTKN-1-0eith07xkcg93lzftuhjmxaxwfa6mbkjsmjzb3d3sx9cobc2zp-97s6xzdt27y2gk3kpm0cgo6y2 192.0.2.41:2377
This node joined a swarm as a worker.
1
2
$ [worker-2] docker swarm join --token SWMTKN-1-0eith07xkcg93lzftuhjmxaxwfa6mbkjsmjzb3d3sx9cobc2zp-97s6xzdt27y2gk3kpm0cgo6y2 192.0.2.41:2377
This node joined a swarm as a worker.

To see the node status, so that we can determine if the nodes are active/available etc, from the manager node, list all the nodes in the swarm:

1
2
3
4
5
[manager] $ docker node ls
ID                           HOSTNAME  STATUS  AVAILABILITY  MANAGER STATUS
j14mte3v1jhtbm3pb2qrpgwp6    worker-1  Ready   Active
siqyf3yricsvjkzvej00a9b8h *  master    Ready   Active        Leader
srl5yzme5hxnzxal2t1efmwje    worker-2  Ready   Active

Reobtaining the Join Tokens

If at any time, you lost your join token, it can be retrieved by running the following for the manager token:

1
$ docker swarm join-token manager -q SWMTKN-1-67chzvi4epx28ii18gizcia8idfar5hokojz660igeavnrltf0-09ijujbnnh4v960b8xel58pmj

And the following to retrieve the worker token:

1
$ docker swarm join-token worker -q SWMTKN-1-67chzvi4epx28ii18gizcia8idfar5hokojz660igeavnrltf0-acs21nn28v17uwhw0oqg5ibwx

Swarm Services in Docker uses a declarative model which means that you define the desired state of the service, and rely on Docker to maintain this state. More information on this can be found on their Documentation

At this moment, we will see that we have no services running in our swarm:

1
2
[manager] $ docker service ls
ID  NAME  MODE  REPLICAS  IMAGE

Deploying our First Service

Now onto the creation of a standard nginx service with 2 replicas, which means that there will be 2 containers of nginx running in our swarm.

But first, we need to create a overlay network, which is a network driver that creates a distributed network among multiple Docker daemon hosts. Swarm takes care of the routing automatically, which is routed via the port mappings. So you can have that your container sits on worker-2, when you hit your manager node on the published port, it will route the request to the desired application that resides on the respective container.

To create a overlay network called mynet:

1
[manager] $ docker network create --driver overlay mynet

Now onto creating the Service. If any of these containers fail, they will handled by the manager node and will be spawned again to have the desired number that we set on the replica option:

1
[manager] $ docker service create --name my-web --publish 8080:80 --replicas 2 --network mynet nginx

Let’s have a look at our nginx service:

1
2
3
[manager] $ docker service ls
ID            NAME    MODE        REPLICAS  IMAGE
1okycpshfusq  my-web  replicated  2/2       nginx:latest

After we see that the replica count is 2/2 our service is ready.

To see on which nodes our containers are running that makes up our service:

1
2
3
4
[manager] $ docker service ps my-web
ID            NAME      IMAGE         NODE      DESIRED STATE  CURRENT STATE           ERROR  PORTS
k0qqrh8s0c2d  my-web.1  nginx:latest  worker-1  Running        Running 30 seconds ago
nku9wer6tmll  my-web.2  nginx:latest  worker-2  Running        Running 30 seconds ago

From the above output, we can see that worker-1 and worker-2 are serving our containers for our service. We can also retrieve more information of our service by using the inspect option, which will give you a detailed response in json format of the service:

1
[manager] $ docker service inspect my-web

We can get the Endpoint Port info by using inspect and using the –format parameter to filter the output:

1
[manager] $ docker service inspect --format="" my-web  | python -m json.tool

From the output we will find the PublishedPort is the Port that we Expose, which will be the listener. Our TargetPort will be the port that is listening on the container:

1
2
3
4
5
6
7
8
[
    {
        "Protocol": "tcp",
        "PublishMode": "ingress",
        "PublishedPort": 8080,
        "TargetPort": 80
    }
]

Now that we went through the inspection of our service, its time to test our base nginx service.

Testing Nginx in our Swarm

Make a request against your docker node manager address on the port that was exposed, in this case 8080:

1
2
3
4
5
6
7
8
9
10
11
$ curl -I http://docker-node-manager-ip:8080

HTTP/1.1 200 OK
Server: nginx/1.15.5
Date: Thu, 10 Jan 2019 14:48:40 GMT
Content-Type: text/html
Content-Length: 612
Last-Modified: Tue, 02 Oct 2018 14:49:27 GMT
Connection: keep-alive
ETag: "5bb38577-264"
Accept-Ranges: bytes

Now we have successfull setup a 3 node docker swarm cluster and deployed a basic nginx service to our swarm. Please have a look at my other Docker Swarm Tutorials for other content.

Thank You

Please feel free to show support by, sharing this post, making a donation, subscribing or reach out to me if you want me to demo and write up on any specific tech topic.

Thanks for reading!

Fix Mac High Sierra Opendlrectoryd Too Many Corpses Being Created Issue

This morning my brother’s iMac gave some boot issues. The resolution to the issue was to drop into a terminal, rename the mrb_cache directory and reboot.

Steps to Resolution

When booting, the loading bar got stuck as seen below:

Starting to investigate, he ran cmd+s to logon to single user mode, and he noticed the error: crashed: opendlrectoryd. Toomay corpses being crashed, as seen from the screenshot below:

After some troubleshooting he had to hard reboot his mac, hit cmd+r repeatedly until he loaded his mac into recovery mode:

From thereon, from the top dropdown select Utilities -> Terminal, change into the directory where the cache folder needs to be moved:

1
$ cd /Volumes/Macintosh\ HD/var/db/caches/opendirectory

List to see if the cache directory is present:

1
2
$ ls -la | grep cache
-rw-------- root wheel 28655   Jan 3    22:22 mbr_cache

Rename the cache directory:

1
mv ./mbr_cache ./mbr_cache_old

Once that is done, reboot:

1
$ reboot

If you experienced the similar issue, you should be able to see the login screen after successful boot.

Thank You

Please feel free to show support by, sharing this post, making a donation, subscribing or reach out to me if you want me to demo and write up on any specific tech topic.


Ad space:

Thanks for reading!

Tutorial on Using Gitlab CI/CD Pipelines to Deploy Your Python Flask Restful API With Postgres on Heroku

Today we will build a Restful API using Python Flask, SQLAlchemy using Postgres as our Database, testing using Python Unittest, a CI/CD Pipeline on Gitlab, and Deployment to Heroku.

From our previous post, we demonstrated setting up a Custom Gitlab Runner on Your Own Server for Gitlab CI.

Heroku

If you don’t have an account already, Heroku offer’s 5 free applications in their free tier account. Once you have created your account, create 2 applications. I named mine flask-api-staging and flask-api-prod.

You can create the applications via cli or the ui, from the ui it will look more or less like this:

Select an app name and check if the name is available then select create. Note down the name and config as we will use it in our .gitlab-ci.yml config:

Heroku API Key

To allow the deployment of applications to Heroku from Gitlab, we need to generate a API Key on Heroku and save the config in Gitlab.

Head over to your Heroku Dashboard, select Account Settings, scroll to the API Key section and generate a API Key.

Head over to your Gitlab Repository, select Settings, CI/CD, then select Variables enter the Key: HEROKU_API_KEY and the Secret of the API Key into the Value and select Save Variable.

We will reference this variable from our deploy steps.

Heroku Postgres Add-on

Heroku offers a free Postgres Add-On, to activate: Select your application, select Resources, search for the Add-on Heroku Postgres, select and select the Hobby Dev Free version and select provision.

Our Application Code

Clone your repository then let’s start by creating our Flask API. Note this is more on Gitlab CI/CD than going into detail into the Flask Application.

Create the files that we will need:

1
$ touch app.py config.cfg requirements.txt tests.py Procfile

Let’s start by populating our configuration for our flask app: config.cfg

1
2
#SQLALCHEMY_DATABASE_URI='sqlite:///database.db'
SQLALCHEMY_TRACK_MODIFICATIONS=False

Our Flask Application: app.py

Note that we are using flask-heroku, with this package Heroku will automatically discover your configuration for your database using environment variables. So if you have a postgres add-on, you don’t need to specify the location of your database.

If you want to use sqlite, you can remove the heroku instantiation and uncomment the SQLALCHEMY_DATABASE_URI property in your config.cfg

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
from flask import Flask, jsonify, request
from flask_sqlalchemy import SQLAlchemy
from flask_marshmallow import Marshmallow
from flask_heroku import Heroku
from passlib.hash import sha256_crypt
from datetime import datetime

app = Flask(__name__)
app.config.from_pyfile('config.cfg')
heroku = Heroku(app)
db = SQLAlchemy(app)
ma = Marshmallow(app)

## --Database Models--
class Member(db.Model):
    __tablename__ = 'members'

    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    email = db.Column(db.String(255), unique=True, nullable=False)
    username = db.Column(db.String(50), unique=True)
    password_hash = db.Column(db.String(100))
    firstname = db.Column(db.String(50), unique=False)
    lastname = db.Column(db.String(50), unique=False)
    registered_on = db.Column(db.DateTime, nullable=False)

class MemberSchema(ma.ModelSchema):
    class Meta:
        model = Member
        fields = ('id', 'username', 'email')

member_schema = MemberSchema(strict=True, only=('id', 'username'))
members_schema = MemberSchema(strict=True, many=True)

## --Views--
@app.route('/')
def index():
    return jsonify({'message': 'ok'}), 200

# list users
@app.route('/api/user', methods=['GET'])
def list_users():
    all_users = Member.query.all()
    result = members_schema.dump(all_users)
    return jsonify(result.data)

# get user
@app.route('/api/user/<int:id>', methods=['GET'])
def get_user(id):
    user = Member.query.get(id)
    result = member_schema.dump(user)
    return jsonify(result.data)

# add user
@app.route('/api/user', methods=['POST'])
def add_user():
    email = request.json['email']
    username = request.json['username']
    password_hash = sha256_crypt.encrypt(request.json['password'])
    firstname = request.json['firstname']
    lastname = request.json['lastname']
    new_user = Member(email=email, username=username, password_hash=password_hash, firstname=firstname, lastname=lastname, registered_on=datetime.utcnow())
    try:
        db.session.add(new_user)
        db.session.commit()
        result = member_schema.dump(Member.query.get(new_user.id))
        return jsonify({'member': result.data})
    except:
        db.session.rollback()
        result = {'message': 'error'}
        return jsonify(result)

# update user
@app.route('/api/user/<int:id>', methods=['PUT'])
def update_user(id):
    user = Member.query.get(id)
    username = request.json['username']
    email = request.json['email']
    user.email = email
    user.username = username
    db.session.commit()
    return member_schema.jsonify(user)

# delete user
@app.route('/api/user/<int:id>', methods=['DELETE'])
def delete_user(id):
    user = Member.query.get(id)
    db.session.delete(user)
    db.session.commit()
    return jsonify({'message': '{} has been deleted'.format(user.username)})

if __name__ == '__main__':
    app.run()

Our tests: tests.py

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
import unittest
import app as myapi
import json
import sys

class TestFlaskApi(unittest.TestCase):
    def setUp(self):
        self.app = myapi.app.test_client()

    def test_hello_world(self):
        response = self.app.get('/')
        self.assertEqual(
            json.loads(response.get_data().decode(sys.getdefaultencoding())),
            {"message": "ok"}
        )

if __name__ == '__main__':
    unittest.main()

Our requirements file: requirements.txt

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
Click==7.0
Flask==1.0.2
flask-heroku==0.1.9
flask-marshmallow==0.9.0
Flask-SQLAlchemy==2.3.2
gunicorn==19.9.0
itsdangerous==1.1.0
Jinja2==2.10
MarkupSafe==1.1.0
marshmallow==2.17.0
marshmallow-sqlalchemy==0.15.0
passlib==1.7.1
psycopg2-binary==2.7.6.1
six==1.12.0
SQLAlchemy==1.2.15
Werkzeug==0.14.1

Our Procfile for Heroku: Procfile

1
web: gunicorn app:app

And lastly, our gitlab-ci configuration which will include our build, test and deploy steps. As soon as a commit to master is received the pipeline will be acticated. Note that our production deploy step is a manual trigger.

Our config for .gitlab-ci.yml. Note to replace your Heroku app names.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
image: rbekker87/build-tools:latest

stages:
  - ver
  - init
  - tests
  - deploy

ver:
  stage: ver
  script:
    - python --version
    - whoami

init:
  stage: init
  script:
    - apk add postgresql-dev --no-cache
    - pip install psycopg2-binary
    - pip install -r requirements.txt

run_tests:
  stage: tests
  script:
    - apk add postgresql-dev --no-cache
    - pip install psycopg2-binary
    - pip install -r requirements.txt
    - python tests.py

deploy_staging:
  stage: deploy
  script:
    - git remote add heroku https://heroku:$HEROKU_API_KEY@git.heroku.com/flask-api-staging.git
    - git push heroku master
    - echo "Deployed to Staging Server https://flask-api-staging.herokuapp.com"
  environment:
    name: staging
    url: https://flask-api-staging.herokuapp.com/
  only:
    - master

deploy_production:
  stage: deploy
  script:
    - git remote add heroku https://heroku:$HEROKU_API_KEY@git.heroku.com/flask-api-prod.git
    - git push heroku master
    - echo "Deployed to Production Server https://flask-api-prod.herokuapp.com"
  environment:
    name: production
    url: https://flask-api-prod.herokuapp.com/
  when: manual
  only:
    - master

Send to Gitlab:

Once everything is populated, stage your changes, commit your work and push to master:

1
2
3
$ git add .
$ git commit -m "blogpost demo commit"
$ git push origin master

Once the code has been pushed to master, gitlab will pick it up and trigger the pipeline to run.

Gitlab Pipelines

Head over to Gitlab, select CI/CD -> Pipelines, you should see a running pipeline, select it, then you should see the overview of all your jobs:

If everything has passed you should see the Passed status as shown above.

You will notice that the staging environment has been deployed. Now you can do some testing and when you are happy with it, you can select the play button which will deploy to production on the pipelines dashboard.

Creating the Tables on Postgres

Before we can interact with our API, we need to provision the postgres tables from the database models that we wrote in our application.

Open up a Python shell on Heroku and initialize the tables:

1
2
3
4
$ heroku run python -a flask-api-prod
>>> from app import db
>>> db.create_all()
>>> exit()

Testing the API:

Now that everything is up and running, its time to test our API.

List the users:

1
2
$ curl https://flask-api-staging.herokuapp.com/api/user
[]

Create a User:

1
2
3
4
5
6
7
$ curl -H 'Content-Type: application/json' -XPOST https://flask-api-staging.herokuapp.com/api/user -d '{"username": "ruanb", "password": "pass", "email": "r@r.com", "firstname": "ruan", "lastname": "bekker"}'
{
  "member": {
    "id": 1,
    "username": "ruanb"
  }
}

List Users:

1
2
3
4
5
6
7
8
$ curl -H 'Content-Type: application/json' -XGET https://flask-api-staging.herokuapp.com/api/user
[
  {
    "email": "ruan@r.com",
    "id": 1,
    "username": "ruanb"
  }
]

Update a User’s email address:

1
2
3
4
5
$ curl -H 'Content-Type: application/json' -XPUT https://flask-api-staging.herokuapp.com/api/user/1 -d '{"username": "ruanb", "email": "ruan@r.com"}'
{
  "id": 1,
  "username": "ruanb"
}

Retrieve a single user:

1
2
3
4
5
6
$ curl -H 'Content-Type: application/json' -XGET https://flask-api-staging.herokuapp.com/api/user/1
{
  "email": "ruan@r.com",
  "id": 1,
  "username": "ruanb"
}

Delete User:

1
2
3
4
$ curl -H 'Content-Type: application/json' -XDELETE https://flask-api-staging.herokuapp.com/api/user/1
{
  "message": "ruanb has been deleted"
}

Troubleshooting

I had some issues with Heroku, where one was after I deployed, I received this error in Heroku’s logs:

1
code=H14 desc="No web processes running" method=GET path="/"

I just had to scale my web dyno to 1:

1
2
$ heroku ps:scale web=1 -a flask-api-staging
Scaling dynos... done, now running web at 1:Free

Have a look at their documentation if you need help with the heroku cli.

And to troubleshoot within the dyno, you can exec into it by running this:

1
heroku ps:exec -a flask-api-staging

I seriously dig Gitlab-CI and with this demonstration you can see how easy it is to setup a CI/CD Pipeline on Gitlab and Deploy them to Heroku.

Resources:

The code for this demo is available at: gitlab.com/rbekker87/demo-cicd-flask-heroku

For more blog posts on Gitlab, have a look at my gitlab category on blog.ruanbekker.com

Thank You

Please feel free to show support by, sharing this post, making a donation, subscribing or reach out to me if you want me to demo and write up on any specific tech topic.


Ad space:

Thanks for reading!

Setup a Gitlab Runner on Your Own Server to Run Your Jobs That Gets Triggered From Gitlab CI

From our previous post, we went through the setup on setting up a Basic CI Pipeline on Gitlab, in conjunction with Gitlab CI which coordinates your jobs, where we used the Shared Runners, which runs your jobs on Gitlab’s Infrastructure.

In Gitlab, you have Shared Runners and your Own Runners, which is used to run your jobs and send the results back to GitLab.

In this tutorial we will Setup a Server with gitlab-runner and Docker on Ubuntu and then Setup a Basic Pipeline to Utilize your Gitlab Runner.

Setup Docker

Install Docker:

1
2
3
4
5
6
7
8
$ sudo apt update && sudo apt upgrade -y
$ sudo apt-get install apt-transport-https ca-certificates curl software-properties-common -y
$ curl -fsSL https://download.docker.com/linux/ubuntu/gpg | sudo apt-key add -
$ sudo add-apt-repository "deb [arch=amd64] https://download.docker.com/linux/ubuntu $(lsb_release -cs) stable"

$ sudo apt update
$ sudo apt install docker-ce -y
$ docker run hello-world

Install and Setup Gitlab Runner

This setup is intended for Linux 64bit, for other distributions, have a look at their docs

Install the Runner:

1
2
3
4
5
$ wget -O /usr/local/bin/gitlab-runner https://gitlab-runner-downloads.s3.amazonaws.com/latest/binaries/gitlab-runner-linux-amd64
$ chmod +x /usr/local/bin/gitlab-runner
$ useradd --comment 'GitLab Runner' --create-home gitlab-runner --shell /bin/bash
$ gitlab-runner install --user=gitlab-runner --working-directory=/home/gitlab-runner
$ gitlab-runner start

Register the Runner. The Gitlab-CI Token is available in your CI/CD Settings panel from the UI: https://gitlab.com/<account>/<repo>/settings/ci_cd

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
$ gitlab-runner register
Please enter the gitlab-ci coordinator URL (e.g. https://gitlab.com/):
https://gitlab.com/

Please enter the gitlab-ci token for this runner:
__masked__

Please enter the gitlab-ci description for this runner:
[my-runner]: my-runner

Please enter the gitlab-ci tags for this runner (comma separated):
my-runner,foobar
Registering runner... succeeded                     runner=66m_339h

Please enter the executor: docker-ssh+machine, docker, docker-ssh, parallels, shell, ssh, virtualbox, docker+machine, kubernetes:
docker

Please enter the default Docker image (e.g. ruby:2.1):
alpine:latest

Runner registered successfully. Feel free to start it, but if it's running already the config should be automatically reloaded!

Verify the Status and check if Docker and Gitlab Runner is enabled on startup:

1
2
3
4
5
6
7
8
9
$ gitlab-runner status
Runtime platform                                    arch=amd64 os=linux pid=30363 revision=7f00c780 version=11.5.1
gitlab-runner: Service is running!

$ systemctl is-enabled gitlab-runner
enabled

$ systemctl is-enabled docker
enabled

Gitlab-CI Config for Shared Runners

If you would like to use the shared runners that Gitlab Offers, the .gitlab-ci.yml config will look like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
stages:
  - build
  - test

build:
  stage: build
  script:
    - echo "this is building"
    - hostname
    - mkdir builds
    - touch builds/data.txt
    - echo "true" > builds/data.txt
  artifacts:
    paths:
      - builds/

test:
  stage: test
  script:
    - echo "this is testing"
    - hostname
    - test -f builds/data.txt
    - grep "true" builds/data.txt

Gitlab-CI Config for your own Gitlab Runner

Gitlab utilizes the tags that was specified on registration to determine where the jobs gets executed on, for more information on this, have a look at their docs

The .gitlab-ci.yml config for using your gitlab runner:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
stages:
  - build
  - test

build:
  stage: build
  tags:
    - my-runner
  script:
    - echo "this is building"
    - hostname
    - mkdir builds
    - touch builds/data.txt
    - echo "true" > builds/data.txt
  artifacts:
    paths:
      - builds/

test:
  stage: test
  tags:
    - my-runner
  script:
    - echo "this is testing"
    - hostname
    - test -f builds/data.txt
    - grep "true" builds/data.txt

Trigger and Check Docker

Commit the config to master, let your pipeline run their jobs upon completion have a look at docker on your server for the containers that the jobs ran on:

1
2
3
4
5
$ docker ps -a
CONTAINER ID        IMAGE               COMMAND                  CREATED              STATUS                          PORTS               NAMES
04292a78de0b        c04b8be95e1e        "gitlab-runner-cache.."  About a minute ago   Exited (0) About a minute ago                       runner-xx-project-xx-concurrent-0-cache-3cxx0
49b1b3c4adf9        c04b8be95e1e        "gitlab-runner-cache.."  About a minute ago   Exited (0) About a minute ago                       runner-xx-project-xx-concurrent-0-cache-6cxxa
422b23191e8c        hello-world         "/hello"                 24 minutes ago       Exited (0) 24 minutes ago                           wizardly_meninsky

As we know each job gets executed in different containers, you can see from the output above that there was 2 different containers for the 2 jobs that was specified in our pipeline.

Resources:

Thank You

Please feel free to show support by, sharing this post, making a donation, subscribing or reach out to me if you want me to demo and write up on any specific tech topic.


Ad space:

Thanks for reading!

Local Dev Environment for Wordpress Using Docker Compose

Let’s setup a local development environment with Docker, Wordpress, MySQL using Docker Compose

Docker Compose File

Let’s look at our docker-compose.yml file:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
version: '3.1'

services:

  wordpress:
    image: wordpress
    restart: always
    ports:
      - 8080:80
    environment:
      - WORDPRESS_DB_NAME=wordpress
      - WORDPRESS_DB_HOST=mysql
      - WORDPRESS_DB_USER=wordpress
      - WORDPRESS_DB_PASSWORD=wordpress
    networks:
      - wordpress

  mysql:
    image: mysql:5.7
    restart: always
    environment:
      - MYSQL_ROOT_PASSWORD=password
      - MYSQL_DATABASE=wordpress
      - MYSQL_USER=wordpress
      - MYSQL_PASSWORD=wordpress
    networks:
      - wordpress

networks:
  wordpress:

Environment Variables for the MySQL Docker image is:

1
2
3
4
5
6
- MYSQL_ROOT_PASSWORD
- MYSQL_DATABASE
- MYSQL_USER, MYSQL_PASSWORD
- MYSQL_ALLOW_EMPTY_PASSWORD
- MYSQL_RANDOM_ROOT_PASSWORD
- MYSQL_ONETIME_PASSWORD

More info can be viewed on this resource: hub.docker.com/_/mysql/

Launching our Wordpress Application:

Lets deploy wordpress:

1
2
3
4
5
$ docker-compose up
Creating network "wordpress_wordpress" with the default driver
Creating wordpress_mysql_1_3e6e3cfe07b1     ... done
Creating wordpress_wordpress_1_a9cb16f277af ... done
Attaching to wordpress_wordpress_1_9227f3d3e587, wordpress_mysql_1_65cc98d222d0

Accessing Wordpress

You should be able to access Wordpress on http://localhost:80/

Local Dev Environment for Mediawiki Using Docker Compose

Let’s setup a local development environment with Docker, Mediawiki, MySQL using Docker Compose

Docker Compose File

Let’s look at our docker-compose.yml file:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
version: "3.4"

services:

  db:
    image: mysql:5.6
    restart: always
    environment:
      - MYSQL_ROOT_PASSWORD=password
      - MYSQL_USER=mw
      - MYSQL_DATABASE=mediawiki
      - MYSQL_PASSWORD=pass
    volumes:
      - /Users/ruan/workspace/docker/mediawiki/mediawiki-mysql-data:/var/lib/mysql
    networks:
      - mediawiki
    ports:
      - 3306:3306

  memcached:
    image: rbekker87/memcached:alpine
    environment:
      - MEMCACHED_USER=memcached
      - MEMCACHED_HOST=0.0.0.0
      - MEMCACHED_PORT=11211
      - MEMCACHED_MEMUSAGE=128
      - MEMCACHED_MAXCONN=1024
    networks:
      - mediawiki

  mediawiki:
    image: benhutchins/mediawiki:latest
    networks:
      - mediawiki
    environment:
      - MEDIAWIKI_DB_TYPE=mysql
      - MEDIAWIKI_DB_HOST=db
      - MEDIAWIKI_DB_USER=mw
      - MEDIAWIKI_DB_PASSWORD=pass
      - MEDIAWIKI_SITE_SERVER=http://localhost
      - MEDIAWIKI_SITE_NAME="My Lekke Wiki"
      - MEDIAWIKI_SITE_LANG=en
      - MEDIAWIKI_ADMIN_USER=admin
      - MEDIAWIKI_ADMIN_PASS=password123
      - MEDIAWIKI_UPDATE=true
      - MEDIAWIKI_ENABLE_SSL=false
    volumes:
      - /Users/ruan/workspace/docker/mediawiki/mediawiki-data:/data
    ports:
      - 80:80
    depends_on:
      - db
      - memcached

networks:
  mediawiki:

Your current working directory in this case: /Users/ruan/workspace/docker/mediawiki

Environment Variables for the MySQL Docker image is:

1
2
3
4
5
6
- MYSQL_ROOT_PASSWORD
- MYSQL_DATABASE
- MYSQL_USER, MYSQL_PASSWORD
- MYSQL_ALLOW_EMPTY_PASSWORD
- MYSQL_RANDOM_ROOT_PASSWORD
- MYSQL_ONETIME_PASSWORD

More info can be viewed on this resource: hub.docker.com/_/mysql/

Launching our Mediawiki Application:

Lets deploy mediawiki:

1
2
3
4
5
$ docker-compose up
Creating network "mediawiki_mediawiki" with the default driver
Creating mediawiki_memcached_1_bbbe8d3fa8b3 ... done
Creating mediawiki_db_1_257775fcf65b        ... done
Creating mediawiki_mediawiki_1_56813d66cbe2 ... done

Accessing Mediawiki

You should be able to access Mediawiki on http://localhost:80/

Resources:

Setup a Basic CI Pipeline on Gitlab

In this tutorial we will setup a Basic CI (Continuous Integration) Pipeline on Gitlab.

The code for this example is available on gitlab.com/rbekker87/demo-ci-basic-pipeline.

If you would like to read more on Continuous Integration / Continuous Deliver (CI/CD).

What will we be doing?

The aim for this is every time there is a commit made to the master branch, that the jobs defined by the .gitlab-ci.yml will be executed and will only pass if exit code 0 has been returned on the scripts.

The jobs gets executed on gitlab runners which is hosted with Giltab. Important to note is that every job runs independently from each other.

Our Basic Pipeline

In this pipeline we will have 2 basic jobs, each job execute a set of scripts:

Build:

1
2
3
4
5
$ echo "this is building" 
$ hostname
$ mkdir builds
$ touch builds/data.txt
$ echo "true" > builds/data.txt

Test:

1
2
3
4
$ echo "this is testing"
$ hostname
$ test -f builds/data.txt
$ grep "true" builds/data.txt

Setup the Pipeline:

From a newly created repository which i’ve cloned to my workspace, create the config:

1
$ touch .gitlab-ci.yml

The config for above yaml file:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
stages:
  - build
  - test

build:
  stage: build
  script:
    - echo "this is building"
    - hostname
    - mkdir builds
    - touch builds/data.txt
    - echo "false" > builds/data.txt
  artifacts:
    paths:
      - builds/

test:
  stage: test
  script:
    - echo "this is testing"
    - hostname
    - test -f builds/data.txt
    - grep "true" builds/data.txt

Config Explained

  • We define 2 stages for this pipeline: build and test
  • We provide context of each job, the stage, the script (commands that will be executed in the lifecycle of the runner) and artifacts (artifacts will be the content that will be transferred, as each job runs in a different runner/container)

Note that I deliberately made a mistake so that my pipeline can fail. I populated the content “false” into the builds/data.txt file from the build job and grep for the word “true” on the test job, so this job will fail.

Push to Github

Save the content to the config file, add, commit and push to master:

1
2
3
$ git add .gitlab-ci.yml
$ git commit -m "add gitlab-ci config"
$ git push origin master

Gitlab Pipelines

From the Gitlab UI, if you head over to CI/CD -> Pipelines, you should see your pipeline running:

When you select the Pipeline ID, you should be presented with the jobs available in your pipeline:

Select Jobs, and you should see an overview of your jobs. At this moment we can see that the build job has completed, and that the test job is busy running:

Shortly thereafter the status of the test job should change to failed, select the Job ID and you should see the output:

From the above output it gives you a link to create a new issue, which is quite handy.

Fix the Pipeline Config

Let’s go ahead and change the content in the .gitlab-ci.yml config and push to master:

1
$ vim .gitlab-ci.yml

Change line 12 from - echo "false" > builds/data.txt to - echo "true" > builds/data.txt, the full content of the file:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
stages:
  - build
  - test

build:
  stage: build
  script:
    - echo "this is building"
    - hostname
    - mkdir builds
    - touch builds/data.txt
    - echo "true" > builds/data.txt
  artifacts:
    paths:
      - builds/

test:
  stage: test
  script:
    - echo "this is testing"
    - hostname
    - test -f builds/data.txt
    - grep "true" builds/data.txt

Commit and push to master:

1
2
3
$ git add .gitlab-ci.yml
$ git commit -m "change content in script"
$ git push origin master

When you head over to Pipelines, you will see that the pipeline is busy running, and on the right the commit that we just made:

Great Success

Select the Pipeline ID, then select Jobs, you should see both jobs succeeded:

Select the Job ID of the test job, and from the output you will see that the job succeeded:

From this output you can also confirm from both jobs, that each job ran in a different runner as the hostnames that was returned to stdout was different.

Resources

This was a really basic example to demonstrate Gitlab CI. Some relevant resources to this post:

Thank You

Please feel free to show support by, sharing this post, making a donation, subscribing or reach out to me if you want me to demo and write up on any specific tech topic.


Ad space:

Thanks for reading!

Resizing Hetzner Cloud Block Storage Volumes on the Fly

Today we will be looking into Hetzner’s Cloud Storage Volumes and how you can resize volumes on the fly!

What is Hetzner’s Cloud Storage Volumes

Hetzner Cloud offers a fast, flexible, and cost-effective SSD based Block Storage which can be attach to your Hetzner Cloud Server. At this point in time its available in the Nuremberg and Helsinki regions.

Resizing of Volumes

Volumes can be resized up to 10TB and the console allows you to resize in 1GB increments. You are allowed to increase, but cannot decrease.

Demo through Cloud Volumes

Let’s run through a demo, where we will do the following:

  • Provision a Server
  • Provision a Volume (XFS Filesystem / EXT4 is also optional)
  • Inspect the Volume, do some performance testing
  • Resize the Volume via Hetzner Cloud Console
  • Grow the XFS Filesystem

After provisioning a server, which takes less than a minute, you should see that the server is created:

SSH into your server. At this moment, we have not provisioned any volumes, so only the root partition should be mounted. Look at the block allocation:

1
2
3
4
5
$ lsblk
NAME   MAJ:MIN RM  SIZE RO TYPE MOUNTPOINT
sda      8:0    0 19.1G  0 disk
--sda1   8:1    0 19.1G  0 part /
sr0     11:0    1 1024M  0 rom

Have a look at the fstab:

1
2
3
4
cat /etc/fstab
# <file system> <mount point>   <type>  <options>       <dump>  <pass>
UUID=2f54e8e6-ff9c-497a-88ea-ce159f6cd283 /               ext4    discard,errors=remount-ro 0       1
/dev/fd0        /media/floppy0  auto    rw,user,noauto,exec,utf8 0       0

And have a look at the mounted disks layout:

1
2
3
4
5
6
7
8
9
$ df -h
Filesystem      Size  Used Avail Use% Mounted on
udev            959M     0  959M   0% /dev
tmpfs           195M  652K  194M   1% /run
/dev/sda1        19G  1.6G   17G   9% /
tmpfs           973M     0  973M   0% /dev/shm
tmpfs           5.0M     0  5.0M   0% /run/lock
tmpfs           973M     0  973M   0% /sys/fs/cgroup
tmpfs           195M     0  195M   0% /run/user/0

Now, time to provision a Volume. Head over to the Volumes section:

I’m going ahead with creating a volume with 10GB of space and assign it to my server, and yeah that’s right, 10GB of storage is 0,40 EUR per month, epic value for money!

After you volume is created, you should see similar output below:

Head back to your server, and have a look at the output when running the similar commands from earlier:

1
2
3
4
5
6
$ lsblk
NAME   MAJ:MIN RM  SIZE RO TYPE MOUNTPOINT
sda      8:0    0 19.1G  0 disk
--sda1   8:1    0 19.1G  0 part /
sdb      8:16   0   10G  0 disk /mnt/HC_Volume_1497823
sr0     11:0    1 1024M  0 rom

The fstab config:

1
2
3
4
5
$ cat /etc/fstab
# <file system> <mount point>   <type>  <options>       <dump>  <pass>
UUID=2f54e8e6-ff9c-497a-88ea-ce159f6cd283 /               ext4    discard,errors=remount-ro 0       1
/dev/fd0        /media/floppy0  auto    rw,user,noauto,exec,utf8 0       0
/dev/disk/by-id/scsi-0HC_Volume_1497823 /mnt/HC_Volume_1497823 xfs discard,nofail,defaults 0 0

The disk layout:

1
2
3
4
5
6
7
8
9
10
$ df -h
Filesystem      Size  Used Avail Use% Mounted on
udev            959M     0  959M   0% /dev
tmpfs           195M  660K  194M   1% /run
/dev/sda1        19G  1.6G   17G   9% /
tmpfs           973M     0  973M   0% /dev/shm
tmpfs           5.0M     0  5.0M   0% /run/lock
tmpfs           973M     0  973M   0% /sys/fs/cgroup
tmpfs           195M     0  195M   0% /run/user/0
/dev/sdb         10G   43M   10G   1% /mnt/HC_Volume_1497823

We can see from the output above how easy it is to provision a volume to your Hetzner Cloud Server. And everything gets done for you, the disk is mounted and the /etc/fstab configuration is populated for you.

Time for some performance testing on the volume:

1
2
3
4
$ dd bs=2M count=256 if=/dev/zero of=/mnt/HC_Volume_1497823/test.dd
256+0 records in
256+0 records out
536870912 bytes (537 MB, 512 MiB) copied, 0.911306 s, 589 MB/s

Pretty neat right? :D

Let’s resize the volume via the Hetzner Cloud Console to 20GB and resize the filesystem. From the Console, head over to the volumes section, select the more options and select resize:

After the volume has been resized, head back to your server and resize the filesystem. As we are using XFS Filesystem, we will use xfs_growfs :

1
2
3
4
5
6
7
8
9
10
11
12
$ xfs_growfs /dev/sdb
meta-data=/dev/sdb               isize=512    agcount=4, agsize=655360 blks
         =                       sectsz=512   attr=2, projid32bit=1
         =                       crc=1        finobt=1 spinodes=0 rmapbt=0
         =                       reflink=0
data     =                       bsize=4096   blocks=2621440, imaxpct=25
         =                       sunit=0      swidth=0 blks
naming   =version 2              bsize=4096   ascii-ci=0 ftype=1
log      =internal               bsize=4096   blocks=2560, version=2
         =                       sectsz=512   sunit=0 blks, lazy-count=1
realtime =none                   extsz=4096   blocks=0, rtextents=0
data blocks changed from 2621440 to 5242880

Have a look at the disk layout and see that the filesystem was resized on the fly. If you have applications writing/reading to and from that volume, its better to unmount it first.

1
2
3
4
5
6
7
8
9
10
$ df -h
Filesystem      Size  Used Avail Use% Mounted on
udev            959M     0  959M   0% /dev
tmpfs           195M  660K  194M   1% /run
/dev/sda1        19G  2.1G   16G  12% /
tmpfs           973M     0  973M   0% /dev/shm
tmpfs           5.0M     0  5.0M   0% /run/lock
tmpfs           973M     0  973M   0% /sys/fs/cgroup
tmpfs           195M     0  195M   0% /run/user/0
/dev/sdb         20G  565M   20G   3% /mnt/HC_Volume_1497823

I must admit, I am really stoked with Hetzner’s offerings and their performance. I’ve been hosting servers with them for the past 5 months and so far they really impressed me.

Have a look at Hetzner Cloud’s offerings, they have great prices as you can start off with a server from as little as 2.49 EUR per month, which gives you 1vCPU, 2GB of RAM, 20GB disk Space and 20TB of traffic. I mean, thats awesome value for money. They also offer Floating IP’s, Backups, etc.

Resources:

Thank You

Please feel free to show support by, sharing this post, making a donation, subscribing or reach out to me if you want me to demo and write up on any specific tech topic.


Ad space:

Thanks for reading!

Creating a UI in Python Flask and Bootstrap for Our Serverless URL Shortener

From a previous post, we went through the setup of building a Serverless URL Shortener with API Gateway, Lambda, and DynamoDB on AWS. Today we will build a Web User Interface using Python Flask, Bootstrap and JavaScript that will communicate to our API to shorten URL’s.

Note: Although using Python Flask is a Hosted option, you could also use this example to host it as a web page on Amazon S3, for the complete serverless route.

Dependencies:

We need Flask, Gunicorn (optional) and Requests:

1
$ pip install flask gunicorn requests

Application Code:

It’s good practice to use a API Key for some level of security, but if not, you can just remove the headers section of x-api-key.

The application relies on 3 environment variables: APP_TITLE - which is the banner name (defaults to “My URL Shortener” if none is set), TINY_API_URL - which is the URL to create the shortened url and X_API_KEY which is the api key for your API.

The content of app.py :

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
from flask import Flask, render_template, request, url_for
import os
import sys
import socket
import requests
import json
import logging

tiny_api_url = os.getenv('TINY_API_URL', None)
tiny_api_key = os.getenv('X_API_KEY', None)
app_title = os.getenv('APP_TITLE', 'My URL Shortener')

if tiny_api_url == None or tiny_api_key == None:
    logging.error("Failed to load configuration")
    sys.exit(4)

headers = {'Content-Type': 'application/json', 'X-Api-Key': tiny_api_key}

app = Flask(__name__)

@app.route('/')
def index():
    return render_template('index.html', app_title=app_title)

@app.route('/shortened', methods=['GET', 'POST'])
def search_request():
    user_url = request.form["input"]
    response = requests.post(
        tiny_api_url,
        headers=headers,
        data=json.dumps({
            "long_url": user_url
            }
        )
    )
    return render_template('results.html', app_title=app_title, res=response.content )

if __name__ == '__main__':
    app.run(passthrough_errors=False)

JavaScript

We want to copy the value of the shortened url response to clipboard when clicking on a button. For that functionality, we need some javascript.

1
2
$ mkdir -p static/js
$ touch static/js/clipboard.js

the content for our javascript function - static/js/clipboard.js :

1
2
3
4
5
function copyToClipboard() {
  var copyText = document.getElementById("input");
  copyText.select();
  document.execCommand("Copy");
}

HTML

The content for templates/index.html :

The content for templates/results.html :

Run the Server

Before we run the server, we need to set the environment variables as mentioned earlier:

1
2
TINY_API_URL=https://tiny-api.mydomain.com/create
X_API_KEY=someRandomSecretKey09876543210

Run the Server:

1
$ gunicorn -w 2 -b 0.0.0.0:8080 --access-logfile=/dev/stdout --error-log=/dev/stderr app:app

After booting the server, access the server on http://localhost:8080/ and the response should look like:

Dockerizing this Application

The source code for this project is available on my github repository

Thank You

Please feel free to show support by, sharing this post, making a donation, subscribing or reach out to me if you want me to demo and write up on any specific tech topic.


VULTR Cloud Servers Limited Signup Promotion

It’s promotion time with VULTR! Get a head start with some free credits.

Promotion

VULTR has a promotion running for a limited time, when you sign up with this link below, use the coupon / promo code: VULTRMATCH and you will receive double the deposit in credits for up to $100. This applies to new customers only.

I’m not quite sure how long they will be running this promotion, but you can get $100 free in credits when you sign up. That is basically 20 months free hosting of a Cloud Server with 1CPU, 1GB RAM, 1TB Bandwidth.

Here’s the link:

About VULTR

If you are not familliar with VULTR, they are a Cloud Hosting Company that offers cloud servers, bare-metal servers and storage servers in 16 different regions and they provide a hourly billing model.

Below are some of their features:

  • 16 Locations: Silicon Valley, Seattle, LA, Dallas, Toronto, Miami, New Jersey, Chicago, Atlanta, London, Paris, Frankfurt, Amsterdam, Tokyo, Singapore, Sydney
  • 100% SLA Guaranteed
  • Solid-State Drives (SSD)
  • Private Networking
  • Reserved IP’s
  • Anti-DDOS Support
  • Backups
  • DNS
  • Startup Scripts
  • Firewalls
  • Pretty Slick User Interface
  • Root Access
  • Hourly Billing
  • Deploy Applications Instantly to your Servers with App Deploys
  • OS Support: Linux, Windows and Custom Uploads
  • API Support
  • Great Documentation and Tutorials

They also allow you to submit articles to them that can earn you up to $300 per article, check it out here

VULTR Mission

From their website, their about us section states:

“Vultr, founded in 2014, is on a mission to empower developers and businesses by simplifying the deployment of infrastructure via its advanced cloud platform. Vultr is strategically located in 16 datacenters around the globe and provides frictionless provisioning of public cloud, storage and single-tenant bare metal.”

“Vultr has made it our priority to offer a standardized highly reliable high performance cloud compute environment in all of the cities we serve. Launching a cloud server environment in 16 cities around the globe has never been easier!”

Launching a Server

I decided to deploy a server pre-configured with Docker, and just about a minute I had my server up and running with Docker, ready to go.

Screenshot of the UI:

Screenshot of the root login:

Overall

I’m quite impressed with VULTR and the ease of use. The pricing is really good and like the fact that you can deploy servers with pre-configured software on it.

Thank You

Please feel free to show support by, sharing this post, making a donation, subscribing or reach out to me if you want me to demo and write up on any specific tech topic.