tim@kolberger.eu
Photo by Francesco Gallarotti on Unsplash

Tutorial: Road to production - Deployment

Once our application is dockerized it can be versatile distributed. We could deploy it to a kubernetes cluster or run it on various cloud platforms like heroku, digital ocean or now. But we want to skip the magic platforms to learn how to deploy and operate our application on our own. So we are going to run the application container with docker-compose on a virtual machine.

There are many VPC providers out there, choose one which fits your needs and budget. You can choose an EC2 instance from AWS, a Virtual Machine from Azure or a Compute Engine from Google Cloud Platform. Last but not least there are cheaper alternatives like linode or contabo.

If you do not want to spend money for a server you can go with VirtualBox or your own machine for intranet use.

Create production docker-compose file

# docker-compose.production.yml

version: '3'

services:
  frontend:
    restart: always
    image: '$FRONTEND_IMAGE'
    env_file:
      - .env

Setup SSH

Your VPS provider should allow SSH access and will transmit the credentials to you. You should now be able to access your VPS with SSH.

Install docker

The following commands should be executed on your VPS.

Follow the official install instructions:

tldr;

# install docker
curl -sSL https://get.docker.com/ | sh
# and test it
docker run hello-world
mkdir -p .docker/frontend
touch .docker/frontend/Dockerfile

Ship it!

You can manually start you application like this

# run once
echo "FRONTEND_IMAGE=<your-frontend-image>" >> .env

# start all containers
docker-compose -f docker-compose.production.yml up -d
# check status
docker-compose -f docker-compose.production.yml ps

Deploy your application with docker-compose on a VPC

# .gitlab-ci/deploy.sh
#!/usr/bin/env sh

echo $CI_REGISTRY_PASSWORD | \
    docker login \
        -u $CI_REGISTRY_USER \
        --password-stdin $CI_REGISTRY

mkdir -p $BASE_PATH
rm -f $BASE_PATH/docker-compose.yml
cp $DOCKER_COMPOSE_FILE $BASE_PATH/docker-compose.yml
cd $BASE_PATH

DOTENV_FILE=.env
cat <<EOF > ${DOTENV_FILE}
FRONTEND_IMAGE=${FRONTEND_IMAGE}

EOF

docker-compose pull
docker-compose down --remove-orphans
docker-compose up -d
docker-compose ps

To execute the deploy script manually we need to set the used environment variables.

# make script executable
chmod +x deploy.sh

export CI_REGISTRY_USER=<your-ci-registry-user>
export CI_REGISTRY=<your-ci-registry>
export BASE_PATH=<your-base-path>
export DOCKER_COMPOSE_FILE=docker-compose.production.yml
export FRONTEND_IMAGE=<your-frontend-image>

 CI_REGISTRY_PASSWORD=<your-ci-registry-password> ./deploy.sh
© 2021 Tim KolbergerDatenschutzerklärung