Smart Machines Musings on the design of smart things

Setting Up Gitlab to Deploy Docker Containers

Linux Containers and Continuous Deployment (CD) tools have greatly simplified the build and deploy process. Now you can bring that simplicity to updating your self-hosted blog. And make your servers smarter in the process.

Consistency Through Automation

Revelux Labs hosts a number of sites on Linode servers and until recently, they were all deployed manually. Currently, the sites are either:

  1. Static and built with Hugo
  2. Built in nodejs with React and Redux.

When Docker became available, we moved the sites into containers and significantly improved our deploy process—building a docker image on a laptop, testing, pushing text files to the server with Git, rebuilding the docker image, and running.

While that was an improvement, there was still a lot of manual work. To fully automate the deployment, we looked at Jenkins, which has a Docker plugin, for deploying our sites.

Jenkins turned out to be overkill for building and deploying a site at a time, so we then looked at Gitlab and it’s CI component–Runner.

And that combination has been just right!

The rest of this post details how we set up Gitlab, a shared runner, and the build scripts for each type of site. It includes:

  • Installing Gitlab
  • Setting Up the Gitlab Runner
  • Creating a Shared Runner Instance
  • The Build Scripts

Installing Gitlab

Sameer Naik has nicely packaged up Gitlab CE in docker containers with linked containers for Gitlab’s dependencies, Postgresql and Redis.

As Sameer describes, you can run the containers like this:

    docker run --name gitlab-postgresql -d \
        --env 'DB_NAME=example_production' \
        --env 'DB_USER=gitlab' --env 'DB_PASS=password' \
        --env 'DB_EXTENSION=pg_trgm' \
        --volume /srv/docker/gitlab/postgresql:/var/lib/postgresql \
        sameersbn/postgresql:9.5

    docker run --name gitlab-redis -d \
        --volume /srv/docker/gitlab/redis:/var/lib/redis \
        sameersbn/redis:latest

    docker run --name gitlab -d \
        --link gitlab-postgresql:postgresql \
        --link gitlab-redis:redisio \
        --publish 10022:22 --publish 10080:80 \
        --env 'GITLAB_PORT=10080' --env 'GITLAB_SSH_PORT=10022' \
        --env 'GITLAB_SECRETS_DB_KEY_BASE=%^BKnM(XEH-ZLgXoHNXYtqVJf&Q' \
        --volume /srv/docker/gitlab/gitlab:/home/git/data \
        sameersbn/gitlab:8.10.4

Data is persisted in /srv/docker/gitlab directory on the host.

These containers assume that there are git and postgres users on the host and that they have specific UID/GID values. These values are used for the ownership and group membership of the mounted data volumes.

You should add these users if your host doesn’t have them and provide the appropriate environment variables in the run commands.

The variables below—added to the docker run command for Gitlab above—sets the git user values for running gitlab.

  ... \
  --env "USERMAP_UID=$(id -u git)" --env "USERMAP_GID=$(id -g git)" \
  ...

A similar change for the postgres container sets the relevant UID/GID there.

Sameer has directions in his documentation.

Setting Up the Gitlab Runner

For our Debian machines, installing the runner was a two-step process.

First, add Gitlab’s repository to the apt source list:

    curl -L https://packages.gitlab.com/install/repositories/runner/gitlab-ci-multi-runner/script.deb.sh | sudo bash

And then use apt-get to install the runner:

    sudo apt-get install gitlab-ci-multi-runner

The install was uneventful, but, because we were building docker containers in the CI scripts, we also needed to give the runner binary access to the docker command line without using sudo. Adding the gitlab-runner user to the docker group does the trick.

    sudo usermod -aG docker gitlab-runner

Creating a Shared Runner Instance

The runner has a broad range of capabilites, most of which were not needed for use cases (i.e., building static sites or nodejs apps in containers). We ended by selecting options in two areas:

  • Executor type
  • Specific vs Shared runners

To support building a wide variety of software stacks, the runner supports six types of executors. After experimenting a bit with docker runners (we always try to put as much in docker as possible, the environment consistency it provides is unmatched), we settled on using a shell executor.

Gitlab provides for runners at the project-level and for shared runners that can be used by multiple projects. For our use case, the shared runner was preferable because only one copy would exist, reducing the load on the host. And we would be running competing jobs.

Gitlab runners are independent of the repository and share data via service calls. And a token is needed to identify the runner to the repository.

For a shared runner, the admin user needs to get the registration token (from the repository-level settings) which is then used in the following command.

    sudo gitlab-ci-multi-runner register -n \
      --url http://example.com:10080/ci \
      --registration-token xxxxxxxxxxxxxxxx \
      --executor shell \
      --description "shell"

Once the shared runner is executing, it is selected in the project settings as the default runner for the project.

The Build Scripts

And last, the final step of the setup is to create a .gitlab-ci.yml file in your projects top-level directory. Gitlab will used this file as a script to execute for building your project.

The following script generates a Hugo site, build a docker image, and then deploys the docker image on the host.

The Gitlab runner uses “stages” to parallelize the build. It has three default stages: build, test, and deploy. The stages list in the script adds a fourth stage—prepare.

It then defines three jobs that run sequentially: pages, build_image, and deploy. Each job has a script, a stage, and a brance for which it applies.

    stages:
      - prepare
      - build
      - test
      - deploy

    before_script:
      - docker info

    pages:
      stage: prepare
      script:
      - hugo
      artifacts:
        paths:
        - public
      only:
      - master

    build_image:
      stage: build
      script:
        - docker build -t revelux/smart_machines .
      only:
        - master

    deploy:
      stage: deploy
      script:
        - ./deploy.sh
      only:
        - master
      environment: production

Gitlab provides detailed documentation on their configuration syntax.

The deploy job uses a shell script to run the docker image once it is built. The script below deploys the container running this blog.

    #! /bin/bash
    docker stop smart
    docker rm smart
    docker run -e VIRTUAL_HOST=www.joh3.io,joh3.io  -p 8200:80 -d --name smart revelux/smart_machines

The CI configuration to build and deploy the node container is very similar, only it omits the prepare job as there is no static site to build.


The automation with Gitlab CI cut 40% of the work from our deploy process for our multiple websites. And, it eliminates the consistency issues that cause failures and stress for the Operations guy.

The next steps are to define some tests to execute before the containers are run. But that’s another post!

Introducción de la Sitting App

Ahora usted puede tener una herramienta que ayude a mejorar su salud sin hacer su rutina diaria más compleja.

Pequeños Cambios para Grandes Ganancias

Los cambios en el estilo de vida de hoy han llevado a tener que estar más períodos sentado (por ejemplo, la escuela, las reuniones, el trabajo de escritorio, la TV). Y la investigación está mostrando que permanecer sentado presenta riesgos para la salud que no pueden ser mitigados por el ejercicio regular. Afortunadamente, la respuesta es fácil: ¡simplemente levántese! ¡Y evite estar sentado!

Como no podemos estar de pie durante todo el día (es agotador y no todos los estudiantes/trabajadores de oficina tienen [escritorios para estar de pie][standingDesk]), necesitamos una herramienta para recordarnos que es tiempo de levantarnos. ¡Y ese teléfono en su bolsillo es lo suficientemente inteligente como para hacer eso!

La Manera Difícil

Existe un número de aplicaciones para el iPhone que sigue sus tiempos de actividad. La mayoría requieren que usted siga su actividad mediante:

*Pulsar un botón para marcar el nivel cuando cambia *Establecer reglas complicadas para empezar los temporizadores que te notificarán cuando levantarte.

Estos enfoques funcionan, pero hacen que todo sea más difícil de lo que debería ser. Nuestra tecnología debe tanto apoyarnos como hacer nuestras vidas más simples, no más complejas. Y existe una forma más inteligente.

La Forma Más Inteligente

Una forma más inteligente de seguimiento de actividad es que el teléfono lo haga por usted, ¡sin reglas ni botones para pulsar!

Imaginemos una aplicación que utilice el acelerómetro de su móvil y algoritmos de aprendizaje para seguir automáticamente sus momentos en los que se encuentra sentado vs. tiempo no sentado. Piense en Watson en su teléfono.

Para ello, la aplicación funcionaría continuamente, incluso en el trasfondo, siguiendo su actividad constantemente. Entonces podría notificarle que esté de pie, después de un intervalo de su elección, sin configurar complicadas reglas o recordar que debe presionar un botón.

La Sitting App

Laboratorios Revelux ha construido esta aplicación y ¡está disponible ahora!

La aplicación le ayuda a controlar automáticamente su tiempo sentado y le alerta cuando ha estado sentado por demasiado tiempo. Realiza un seguimiento de sus momentos sentado versus. el tiempo no sentado, o activo, y le notifica: “Parece v muévase”, después de un período de tiempo definido por el usuario. Y utiliza aprendizaje de maquina para clasificar su actividad continuamente.

La aplicación detiene la actividad de seguimiento cuando se establece sobre una superficie estable (p. ej. el escritorio para cargar).

Ya que corre continuamente en el trasfondo, la Sitting app también se detiene cuando la batería se agota, la aplicación se detiene en el selector de aplicaciones o al reiniciar el teléfono. Se puede reiniciar fácilmente abriendo la aplicación otra vez.

La Sitting app puede mostrar minutos sentado como una insignia en el icono. Proporciona un gráfico de barras de su actividad diaria sobre la vida de la aplicación y puede incluso compartir la actividad de la semana con sus amigos.

La Sitting App es gratuita (con compras dentro de la aplicación) y está disponible en localizaciones en inglés, chino (simplificado), francés y español.

¡Descargue hoy! su Sitting y comienza a levantarte más y a sentarte menos, automáticamente.

Introducing the Sitting App

Now you can have a tool that helps improve your health without making your daily routine more complex.

Small Changes for Big Gains

Changes in today’s lifestyles have led to longer and longer periods of sitting (e.g., school, desk work, meetings, tv). And, research is showing that prolonged sitting introduces health risks that cannot be mitigated by regular exercise. Fortunately, the answer is easy: simply stand up! And avoid sitting down!

Because we can’t stand all day (it’s tiring and not all students/office workers have standing desks), we need a tool to remind us that it’s time to stand. And that phone in your pocket is smart enough to do that!

The Hard Way

A number of apps exist for the iPhone that track your activity time. Most of them require that you track your activity by:

  • Pressing a button to mark the level when it changes
  • Set up complicated rules to start timers that will notify you to stand up.

These approaches work, but they make it much harder than it needs to be. Our tech should both support us and make our lives simpler, not more complex. And, a smarter way exists.

The Smarter Way

A smarter way to track activity is to have your phone do it for you, without rules or buttons to be pressed!

Imagine an app that uses your phone’s accelerometer and state-of-the-art machine learning algorithms to automatically track your sitting vs. non-sitting time. Think Watson in your phone.

To do this, the app would run continuously, even in the background, constantly tracking your activity. Then it could notfiy you to stand–after an interval of your choosing–without setting up complicated rules or remembering to press a button.

The Sitting App

Revelux Labs has built this app and it is available now!

The app helps you to automatically monitor your sitting time and can alert you when you’ve been sitting too long. It tracks your sitting vs. non-sitting or active time and notifies you to “Stand up and move” after a user-defined time period. And it uses machine learning to continuously classify your activity.

The app stops tracking activity when you set it on a stable surface (e.g. the desk for charging).

Because it runs continuously in the background, the Sitting app also stops when the battery dies, the app is killed in the application switcher, or the phone reboots. It can be easily restarted by opening the app again.

The Sitting app can display the minutes sitting as a badge on the icon. It provides a bar graph of your daily activity over the life of the app and can even share the week’s activity with your friends.

The Sitting App is free (with in-app purchases) and available in English, Chinese(simplified), French, and Spanish localizations.

Download Sitting today! And start standing more and sitting less–automatically.

Introduire l’App Assis

Maintenant vous pouvez avoir un outil qui permet d’améliorer votre santé sans faire votre routine quotidienne plus complexe.

Petits changements pour les gros gains

Les changements des modes de vie d’aujourd’hui ont conduit à des périodes plus longues et plus longues de la séance (p. ex., école, travail de bureau, réunions, tv). Et, la recherche montre que séance prolongée présente des risques pour la santé qui ne peuvent être atténués par des exercices réguliers. Heureusement, la réponse est simple : il suffit *stand up* ! Et éviter *assis en bas* !

Parce que nous ne pouvons pas rester toute la journée (c’ est fatiguant et pas tous les étudiants/travailleurs de bureau ont pupitre de commandes), nous avons besoin d’un outil pour nous rappeler qu’il est temps de se tenir. Et que le téléphone dans votre poche est assez intelligent pour faire ça !

La façon dure

Il existe plusieurs applications pour iPhone qui suit votre temps d’activité. La plupart d’entre eux exigent que vous suivez votre activité en :

  • En appuyant sur un bouton pour marquer le niveau quand il change
  • Mettez en place des règles compliquées pour déclencher les minuteries qui vous informeront quand vous vous devez lever.

Ces méthodes fonctionnent, mais ils le rendent beaucoup plus difficile qu’il doit être. Notre tech devrait aussi bien nous soutenir et rendent notre vie plus simple, pas plus complexe. Et, il existe une façon plus intelligente.

La manière la plus intelligente

Une façon plus intelligente pour suivre l’activité est de demander à votre téléphone de le faire pour vous, sans règles et sans appuyer sur aucun bouton !

Imaginez une application qui utilise l’accéléromètre de votre téléphone et les algorithmes machine learning de pointe pour suivre automatiquement le temps que êtes assis vs. le temps que vous n’êtes pas assis. Pensez Watson dans votre téléphone.

Pour faire ça, l’application irait en permanence, même dans le fond, constamment suivi de votre activité. Puis il vous avertira de se tenir - après un intervalle de votre choix - sans mettre en place des règles compliquées pour se souvenir d’appuyer sur un bouton.

L’App de séance

Revelux Labs a créé cette application et elle est disponible maintenant !

L’application vous aide à surveiller automatiquement votre temps de la séance et peut vous avertir lorsque vous avez été assis trop longtemps. Il suit votre séance vs. non-séance ou le temps actif et vous avertit de «Levez-vous et déplacez» après une période de temps définie par l’utilisateur. Et il utilise l’apprentissage de la machine à classer en permanence votre activité.

L’application arrête de suivre l’activité lorsque vous la mettez sur une surface stable (par exemple, le bureau pour la charger).

Parce qu’il fonctionne en permanence en arrière-plan, l’app de séance aussi s’arrête quand la batterie meurt, l’app est tuée dans la fonction permutation d’applications, ou le téléphone redémarre. Il peut être facilement redémarré en ouvrant l’application à nouveau.

L’app de séance peut afficher les minutes assis comme un insigne sur l’icône. Il fournit un diagramme à barres de votre activité quotidienne pendant la durée de l’application et peut même partager l’activité de la semaine avec vos amis.

L’App Assis est gratuit (avec achats in-app) et disponible en des localisations chinoises (simplifiées), anglaises, françaises et espagnoles .

Téléchargez Sitting aujourd’hui ! Et commencez à vous lever plus et à vous assoir moins –automatiquement.

介绍坐姿 App

现在您可以有一种可以帮助您改善健康的工具,却不会让您的日常生活更复杂。

小改变,大获益

现今生活方式的改变导致了漫长的久坐 (例如,学校丶办公室工作 丶 会议丶 电视)。 而且,研究表示 久坐 引起的健康风险无法被规律的身体锻炼减轻。 幸运的是,答案很简单︰ 只需 * 站起来 * ! 避免 * 坐下来 * !

由于我们不能忍受一整天都站立着 (这是累人的,而且并不是所有的学生/办公室员工拥有 立式办公桌),我们需要一款工具来提醒我们站立的时刻。 而你口袋中的电话可以聪明到足以办到这一点!

不方便的方式

iphone 平台上有大量的应用程序追踪您的活动时间。 其中绝大多数需要* 您 * 跟踪您的活动︰

  • 当活动改变时,按下一个按钮来标记水平
  • 设置复杂的规则来启动计时以通知您站起来

这个方式是有效的,可是它看起来如此艰难。 我们的技术应支持我们并使我们的生活更轻松,而不是更复杂。 有一种更聪明的方式存在着。

更聪明的方式

跟踪活动的更聪明的方式是让您的手机帮您实现目标,无需规则,仅是按按钮!

想象一个应用程序是使用您手机的加速度传感器和先进的机器学习算法来自动跟踪您坐着的时间 和对应的非坐着的时间。 想想您手机上的 Watson.

为达到这个目标,这款应用程序会连续运行,即使在背景中也不断地跟踪您的活动。 它也能针对你选择的时间间隔通知你是时候站立了,而你无需设定复杂的规则或得记得按按钮。

站立应用程式

Revelux 实验室 开发了这款应用程序,它现在已可下载 !

应用程序可帮助您自动监视您坐的时间,当您已经坐得太久时可以提醒您。 它追踪您坐着的时间 和相对的非坐着或活动的时间,并在用户自定义的时间周期后通知您”站起来和移动”。 它使用机器学习来不断分类您的活动。

当你将它放在平稳的表面(放在桌子充电), 应用程式会停止跟踪活动。

因为它可连续在后台运行,因此站立应用程式在电池消耗完了就会停止运作,使用应用程式切换程序或在手机重启时,本应用程式将停止运作。 但重新开启应用程式就能使它再次运作起来。 站立应用程序能作为图标标记显示坐着的分钟。 它提供您的日常活动条形图,你甚至可以与你的朋友共享一周的活动时间记录。

站立应用程序是免费的 (应用程序虚拟店内购买) ,而且提供英语、 中文 (简体)、 西班牙语和法语版本。

今天就下载 Sitting吧 ! 并自动地开始多站少坐 。