Alisson Machado
18 February 2018

Minishift: Openshift Origin como ambiente de desenvolvimento

O Minishift é uma versão simplificada do Openshift Origin que pode ser instalada dentro do VirtualBox e utilizada como ambiente de desenvolvimento, esse post tem como objetivo mostrar a instalação e utilização dessa plataforma até o deploy de aplicações em diferentes linguagens. Não se esqueça de que o virtualbox é um pre requisito: https://www.virtualbox.org/


O repositório oficial do minishift segue abaixo: https://github.com/minishift/minishift Para fazer a instalação é relativamente simples, já estou considerando que o VirtualBox está instalado, caso você não tenha ele pode ser baixo neste link: https://www.virtualbox.org/wiki/Downloads Abaixo o passo a passo da instalação:

alisson@alisson-avell:~$ wget https://github.com/minishift/minishift/releases/download/v1.13.1/minishift-1.13.1-linux-amd64.tgz
alisson@alisson-avell:~$ tar -xf minishift-1.13.1-linux-amd64.tgz
alisson@alisson-avell:~$ sudo mv minishift-1.13.1-linux-amd64/minishift /usr/local/bin/ -v
'minishift-1.13.1-linux-amd64/minishift' -> '/usr/local/bin/minishift'
alisson@alisson-avell:~$ rm -rf minishift-1.13.1-linux-amd64


Pronto, você já tem o minishift instalado, para validar se está funcionando digite o comando abaixo:

alisson@alisson-avell:~$ minishift --help


Minishift is a command-line tool that provisions and manages single-node OpenShift clusters optimized for development workflows.

Usage:
  minishift [command]

Available Commands:
  addons      Manages Minishift add-ons.
  completion  Outputs minishift shell completion for the given shell (bash or zsh)
  config      Modifies Minishift configuration properties.
  console     Opens or displays the OpenShift Web Console URL.
  delete      Deletes the Minishift VM.
  docker-env  Sets Docker environment variables.
  help        Help about any command
  hostfolder  Manages host folders for the OpenShift cluster.
  image       Exports and imports container images.
  ip          Gets the IP address of the running cluster.
  logs        Gets the logs of the running OpenShift cluster.
  oc-env      Sets the path of the 'oc' binary.
  openshift   Interacts with your local OpenShift cluster.
  profile     Manages Minishift profiles.
  ssh         Log in to or run a command on a Minishift VM with SSH.
  start       Starts a local OpenShift cluster.
  status      Gets the status of the local OpenShift cluster.
  stop        Stops the running local OpenShift cluster.
  update      Updates Minishift to the latest version.
  version     Gets the version of Minishift.

Flags:
      --alsologtostderr                  log to standard error as well as files
  -h, --help                             help for minishift
      --log_backtrace_at traceLocation   when logging hits line file:N, emit a stack trace (default :0)
      --log_dir string                   If non-empty, write log files in this directory (default "")
      --logtostderr                      log to standard error instead of files
      --profile string                   Profile name (default "minishift")
      --show-libmachine-logs             Show logs from libmachine.
      --stderrthreshold severity         logs at or above this threshold go to stderr (default 2)
  -v, --v Level                          log level for V logs
      --vmodule moduleSpec               comma-separated list of pattern=N settings for file-filtered logging

Use "minishift [command] --help" for more information about a command.


Com o minishift já funcionando, vamos subir a máquina virtual com o openshift origin já instalado, então digite o comando abaixo:

alisson@alisson-avell:~$ minishift start --vm-driver virtualbox


-- Starting profile 'minishift'
-- Checking if requested hypervisor 'virtualbox' is supported on this platform ... OK
-- Checking if VirtualBox is installed ... OK
-- Checking the ISO URL ... OK
-- Starting local OpenShift cluster using 'virtualbox' hypervisor ...
-- Minishift VM will be configured with ...
   Memory:    2 GB
   vCPUs :    2
   Disk size: 20 GB

   Downloading ISO 'https://github.com/minishift/minishift-b2d-iso/releases/download/v1.2.0/minishift-b2d.iso'
 40.00 MiB / 40.00 MiB [============================================] 100.00% 0s
-- Starting Minishift VM ............................ OK
-- Checking for IP address ... OK
-- Checking if external host is reachable from the Minishift VM ... 
   Pinging 8.8.8.8 ... OK
-- Checking HTTP connectivity from the VM ... 
   Retrieving http://minishift.io/index.html ... OK
-- Checking if persistent storage volume is mounted ... OK
-- Checking available disk space ... 0% used OK
   Importing 'openshift/origin:v3.7.1'  CACHE MISS
   Importing 'openshift/origin-docker-registry:v3.7.1'  CACHE MISS
   Importing 'openshift/origin-haproxy-router:v3.7.1'  CACHE MISS
-- Downloading OpenShift binary 'oc' version 'v3.7.1'
 38.51 MiB / 38.51 MiB [============================================] 100.00% 0s-- Downloading OpenShift v3.7.1 checksums ... OK
-- OpenShift cluster will be configured with ...
   Version: v3.7.1
-- Checking 'oc' support for startup flags ... 
   host-config-dir ... OK
   host-data-dir ... OK
   host-pv-dir ... OK
   host-volumes-dir ... OK
   routing-suffix ... OK
Starting OpenShift using openshift/origin:v3.7.1 ...
Pulling image openshift/origin:v3.7.1
Pulled 1/4 layers, 26% complete
Pulled 1/4 layers, 29% complete
Pulled 1/4 layers, 32% complete
Pulled 1/4 layers, 35% complete
Pulled 1/4 layers, 39% complete
Pulled 1/4 layers, 43% complete
Pulled 1/4 layers, 42% complete
Pulled 1/4 layers, 45% complete
Pulled 1/4 layers, 47% complete
Pulled 1/4 layers, 49% complete
Pulled 1/4 layers, 52% complete
Pulled 1/4 layers, 54% complete
Pulled 1/4 layers, 57% complete
Pulled 1/4 layers, 59% complete
Pulled 1/4 layers, 62% complete
Pulled 1/4 layers, 66% complete
Pulled 1/4 layers, 69% complete
Pulled 1/4 layers, 72% complete
Pulled 1/4 layers, 75% complete
Pulled 2/4 layers, 79% complete
Pulled 3/4 layers, 85% complete
Pulled 3/4 layers, 87% complete
Pulled 3/4 layers, 89% complete
Pulled 3/4 layers, 91% complete
Pulled 3/4 layers, 92% complete
Pulled 3/4 layers, 94% complete
Pulled 3/4 layers, 97% complete
Pulled 3/4 layers, 100% complete
Pulled 4/4 layers, 100% complete
Extracting
Image pull complete
OpenShift server started.

The server is accessible via web console at:
    https://192.168.99.100:8443

You are logged in as:
    User:     developer
    Password: 

To login as administrator:
    oc login -u system:admin

-- Exporting of OpenShift images is occuring in background process with pid 11656.


Ao final da execução do comando, note que foi dado a url de acesso e o login.

The server is accessible via web console at:
    https://192.168.99.100:8443

You are logged in as:
    User:     developer
    Password: 

To login as administrator:
    oc login -u system:admin


Ao acessar a url, será carregada a página abaixo:

Essa e a tela de login do openshift


logue com o usuário developer, e a senha tanto faz, pode ser teste. Ao fazer o login essa será a tela inicial: Nessa tela voce pode ver todos os templates the aplicacoes como Java, PHP e Python e os botoes para criar um novo projeto


Clique em Python, depois em next e preencha os dados conforme a imagem abaixo:

Nessa dela voce deve preencher com o repositorio da sua aplicacao e o nome da apliacacao


O repositório configurado é esse: https://github.com/AlissonMMenezes/python-openshift.git


Agora clique em My Projects no canto direto, será carregada a seguinte tela:


Nessa tela e descrito o seu deployment criado e que ainda esta em execucao


Agora é só aguardar nessa tela para que os pods sejam criados, uma vez criados a tela ficará conforme desta forma:


Nessa tela e possivel ver que um pod ja foi criado e esta em execucao


A url em que foi publicada a aplicação foi essa: http://hello-openshift-myproject.192.168.99.103.nip.io , agora é só clicar em acessar e ver que a aplicação já está no ar.


Nessa imagem e possivel ver o navegador com a aplicacao em execucao exibindo uma mensagem de hello world


E assim terminamos o deploy de uma aplicação em python dentro do openshift origin. Para fazer a publicação de uma aplicação em PHP, eu vou fazer via linha de comando para mostrar a diferença, nesse caso precisamos instalar o comando oc, para isso é necessário seguir este passo a passo:


alisson@alisson-avell:~$ wget https://github.com/openshift/origin/releases/download/v1.5.1/openshift-origin-client-tools-v1.5.1-7b451fc-linux-64bit.tar.gz
alisson@alisson-avell:~$ tar -xf openshift-origin-client-tools-v1.5.1-7b451fc-linux-64bit.tar.gz 
alisson@alisson-avell:~$ cd openshift-origin-client-tools-v1.5.1-7b451fc-linux-64bit/
alisson@alisson-avell:~/openshift-origin-client-tools-v1.5.1-7b451fc-linux-64bit$ ls
LICENSE  oc  README.md
alisson@alisson-avell:~/openshift-origin-client-tools-v1.5.1-7b451fc-linux-64bit$ sudo mv oc /usr/local/bin/ -v
[sudo] password for alisson: 
'oc' -> '/usr/local/bin/oc'


Agora vamos fazer o login via linha de comando para fazer o deploy da aplicação em PHP.

alisson@alisson-avell:~$ oc login -u system:admin
Logged into "https://192.168.99.100:8443" as "system:admin" using existing credentials.

You have access to the following projects and can switch between them with 'oc project ':

    default
    kube-public
    kube-system
  * myproject
    openshift
    openshift-infra
    openshift-node

Using project "myproject".


Note que automaticamente já estamos no projeto myproject, é nele que vamos publicar a aplicação em PHP, para fazer isso digite o comando:

alisson@alisson-avell:~$ oc new-app centos/php-70-centos7~https://github.com/AlissonMMenezes/php-openshift.git


--> Found Docker image 7f2bb5a (10 days old) from Docker Hub for "centos/php-70-centos7"

    Apache 2.4 with PHP 7.0 
    ----------------------- 
    PHP 7.0 available as docker container is a base platform for building and running various PHP 7.0 applications and frameworks. PHP is an HTML-embedded scripting language. PHP attempts to make it easy for developers to write dynamically generated web pages. PHP also offers built-in database integration for several commercial and non-commercial database management systems, so writing a database-enabled webpage with PHP is fairly simple. The most common use of PHP coding is probably as a replacement for CGI scripts.

    Tags: builder, php, php70, rh-php70

    * An image stream will be created as "php-70-centos7:latest" that will track the source image
    * A source build using source code from https://github.com/AlissonMMenezes/php-openshift.git will be created
      * The resulting image will be pushed to image stream "php-openshift:latest"
      * Every time "php-70-centos7:latest" changes a new build will be triggered
    * This image will be deployed in deployment config "php-openshift"
    * Ports 8080/tcp, 8443/tcp will be load balanced by service "php-openshift"
      * Other containers can access this service through the hostname "php-openshift"

--> Creating resources ...
    imagestream "php-70-centos7" created
    imagestream "php-openshift" created
    buildconfig "php-openshift" created
    deploymentconfig "php-openshift" created
    service "php-openshift" created
--> Success
    Build scheduled, use 'oc logs -f bc/php-openshift' to track its progress.
    Run 'oc status' to view your app.


No comando centos/php-70-centos7~https://github.com/AlissonMMenezes/php-openshift.git, temos primeiro a imagem do Docker que será utilizada, centos/php-70-centos7 e após o ~, temos o repositório onde está armazenado o código fonte da aplicação, https://github.com/AlissonMMenezes/php-openshift.git . Agora volte na interface Web e veja que a aplicação já foi publicada.


Nessa imagem foram seguidos os mesmos passos mas para publicar uma aplicacao em PHP


Mas note que essa aplicação ainda não tem uma rota para o acesso externo, então para criar via linha de comando, podemos fazer digitando os seguintes comandos: Primeiro vams identificar o nome do service que corresponde a aplicação.

alisson@alisson-avell:~$ oc get svc
NAME              CLUSTER-IP       EXTERNAL-IP   PORT(S)             AGE
hello-openshift   172.30.195.123           8080/TCP            1h
php-openshift     172.30.183.7             8080/TCP,8443/TCP   1h
teste             172.30.99.138            8080/TCP            1h


Agora expor esse service com um hostname.

alisson@alisson-avell:~$ oc expose service php-openshift --hostname=testephp.192.168.99.103.nip.io
route "php-openshift" exposed


Agora no dashboard já pode ser visto o serviço publicado como testephp.192.168.99.103.nip.io .


Aqui e possivel ver que o container foi deployado com sucesso


E por fim a aplicação publicada.


Aqui novamente no navegador com um Hello World me PHP