# 8 DevOps

8.1 Docker

Livro Descomplicando Docker

Github

8.1.1 Part 1

8.1.1.1 O que é container ?

Container não é virtualização e sim isolamento

  • Isolamento lógico Responsável Namesapace
    • parte usuaŕios e processos
    • como se tivessemos isolado um pedaço da máquina para o container
    • dentro do container tenho isolamento de network, cada container tem sua interface
  • Isolamento de físico _"Responsável Cgroup"
    • recursos : CPU, RAM, IO rede, IO de bloco, etc

8.1.1.2 O que é o Docker ?

  • Uma imagem de container é divida em camadas e so se escreve na última camanda , as abaixo são somente leitura

  • Instalar

curl -fsSL https://get.docker.com | bash
  • Versão instalada
root@turing:~# docker version
Client: Docker Engine - Community
 Version:           20.10.8
 API version:       1.41
 Go version:        go1.16.6
 Git commit:        3967b7d
 Built:             Fri Jul 30 19:54:22 2021
 OS/Arch:           linux/amd64
 Context:           default
 Experimental:      true

Server: Docker Engine - Community
 Engine:
  Version:          20.10.8
  API version:      1.41 (minimum version 1.12)
  Go version:       go1.16.6
  Git commit:       75249d8
  Built:            Fri Jul 30 19:52:31 2021
  OS/Arch:          linux/amd64
  Experimental:     false
 containerd:
  Version:          1.4.9
  GitCommit:        e25210fe30a0a703442421b0f60afac609f950a3
 runc:
  Version:          1.0.1
  GitCommit:        v1.0.1-0-g4144b63
 docker-init:
  Version:          0.19.0
  GitCommit:        de40ad0
root@turing:~# 
  • Adicionar usuário ao grupo do docker
usermod -aG docker <user>
  • Listar os containers
docker container ls
  • Hello World
docker container run -ti hello-world
  • Steps that docker perform on docker container run ….:
 1. The Docker client contacted the Docker daemon.
 2. The Docker daemon pulled the "hello-world" image from the Docker Hub.
    (amd64)
 3. The Docker daemon created a new container from that image which runs the
    executable that produces the output you are currently reading.
 4. The Docker daemon streamed that output to the Docker client, which sent it
    to your terminal.

8.1.1.3 Commandos básicos

  • Listar todas as imagens :
docker container ls -a
  • Lista todos os containers rodando :
docker container ls
  • Exemplo criar um container
    • -ti : Terminal e interatividade
    • Ctrl D : mata o bash o principal processo do container e o container é finalizado
    • Ctrl q p: Para sair do container sem encerrar o bash e container
    • -d : Para colocar o container como daemon
docker run -it ubuntu bash
  • Reconectar ao container :
docker container attach <Container ID ou  nome>
  • Remover o container :
docker container rm <ID ou nome>
  • Stop / Start / Restart / Pause container :
    • Stop : docker container stop <container ID ou nome>
    • Start: docker container start <container ID ou nome>
    • Restart : docker container restart <container ID ou nome>
    • Pause : docker container pause <container ID ou nome>
    • Unpause : docker container unpause <container ID ou nome>
  • Informações do container :
docker container inspect <container ID ou nome>
  • Logs :
docker container logs -f <ID ou nome>
  • Update para fazer atualização em um container em execução
docker container update
  • Listar as imagens
docker image ls

8.1.1.4 CPU and RAM - containers

  • Para verificar o quanto o docker esta utilizando de recursos
docker container stats <container ID>
  • Verificar os processos
docker container top <container ID>
  • Liminar o máximo de memória que o container nginx pode utilizar com parametro m
# Limitando a memória em 128M
docker container run -d -m 128M nginx
  • Limitar a CPU
# Limitando a CPU em 50% ou meio CPU
docker container run -d -m 128M --cpus 0.5 nginx
  • Para fazer teste de stress utilizando pacote stress do linux
# Para instalar o stress
apt-get update && apt-get install -y stress


stress -cpu 1 -vm 1 --vm-bytes 64M

8.1.1.5 Docker file Basic

sample of simple docker file

FROM debian     

LABEL app="Giro"
ENV VAR_1="sample variable"


RUN apt-get update && apt-get install -y stress && apt-get clean

CMD = stress --cpu 1 --vm-bytes 64M --vm 1

To build

docker image build`-t <nome>:<versao> .

To run

docker container run -d <nome>:<versao>

8.1.2 Part 2

8.2 Jenkins

GitHub Repository from instructor

8.2.1 CI/CD

  • Continuous Integration / Continuous Delivery - Practice to delivery the ready to deploy code
  • CI : multiple integration per day

  • CD : build allowed to deploying for customer anytime

8.2.2 Install

Recommendation

  • 1GB RAM

  • 50GB Disk

  • Java 8

  • Linux / Win / Mac

  • To install install Jenkins Long Term Support on RedHat system

Guide

sudo wget -O /etc/yum.repos.d/jenkins.repo \
    https://pkg.jenkins.io/redhat-stable/jenkins.repo
sudo rpm --import https://pkg.jenkins.io/redhat-stable/jenkins.io.key
sudo yum upgrade
sudo yum install epel-release java-11-openjdk-devel
sudo yum install jenkins
sudo systemctl daemon-reload
  • To start Jenkins
sudo systemctl start jenkins
sudo systemctl status jenkins
  • We will need the password for initial configuration at /var/lib/jenkins/secrets/initialAdminPassword

8.2.3 Arquitecture

Jenkins follow the master/slave architecture

  • Master Node : controller, that controls the Load Distribution on Slave Node

    • Used to schedule the build Job
    • Dispatch Build Execution to Slave Node
    • Monitor Slave and Record the Build Results
  • Worker Node : Execution Node, we can have several slave nodes

    • Execute Build dispatched by Master
    • Not require Jenkins, only JAVA

8.2.4 Job

  • Job is any runnable task that is controlled by Jenkins

    • FreeStyle Project : Shell or Bash commands
    • Pipeline : Workflow, usually written in DSL
    • Multi Configuration Project : Will be tested on Multiple environments

8.2.5 Git & GitHub

8.3 Git

8.3.1 Intro

Some Concepts

  • Commit :

    • Saved changes to git repository
    • Impacts history
    • SHA1 hash for unique identifier
  • Branches:

    • Timeline with commits
  • HEAD

    • Pointer to last commit on branch
  • Remote

    • Related repository - but not local
    • GitHub, GitLab, Bitbucket, etc

Git Workflow

Starting Local :

  1. Init the working directory
  2. Add files , etc
  3. Staging the changes using git add command
  4. Commit the changes using commit command
  5. Push the changes on remote repository

Everyone can now pull the changes back

Starting remotely:

  1. Create a new repository on Git remote, like Github
  2. Clone the repository to create it locally
  3. Do the work,add files
  4. Send the changes to staging area using git add command
  5. Commit the changes
  6. Send the data to remote repository using git push

8.3.2 Setup and Config

  1. Configure the name and email
git config --global user.name "<Name>"

git config --global user.email "<email>"
  1. To confirm the set :
git config --global --list

We also can check the config on ~/.gitconfig file

8.3.3 Working Locally

  • Starting a fresh repository
git init <repo_name>

# Or inside a folder just git init

git init

see that inside the folder will be create a .git file

  • After create some files can check the status of track files using status command
git status
  • To add a file in the staging area
git add <file>  

# or add all files

git add . 
  • Commit
git commit -m "<message>"
  • Add and commit at the same time, just one step
git commit -am "<message>"
  • To remove a file from the staging area, this will “unstage” the specified file from Git Staging area
git reset HEAD <file>
  • To back out a change in a file , this command will replace the file with the version last committed in Git
git checkout -- <file>
  • List all the commits done in the repo

git log

# or compat view

git log --oneline --graph --decorate --color
  • Back out changes already committed
git rm <file>

git commit -m "<message>"
  • If remove the file using rm OS command need to do the below steps
git add -u 
git status
git commit -m "<msg>"
git status
  • Moving a file
mkdir subdir

git mv <file> <subdir>

git status

git commit -m "<msg>"

if move the file without git need to use -u command on git add step

  • Ignoring files using .gitignore file

add on .gitignore

# ignoring all .log files
*.log

8.3.4 Working Remote

  • Configure your .ssh key
mkdir ~/.ssh
cd ~/.ssh
ssh-keygen -t rsa -C "email"  

<enter>

This process will create two files , id_rsa and id_rsa.pub the content of .pub we will add into github account on SSH Keys setting.

  • To test
ssh -T git@github.com
  • If we create a new repo from internet application we can use the below command to associate our local repo to remote repository
git remote add origin git@github.com:<user>/<repo_name>.git
  • To push the files from local to remote repository
git push -u origin master

This will send all files from local to remote, second time we will not be need to use -u paramter

  • Now before perform a commit it is important to check if there are any modification by others
git pull origin master
  • Push the changes
git push origin master

The push sends all local changes on branch to the remote. The parameter -u is needed the fist time you push a branch to the remote.

The pull receives all your remote changes fro the remote to local