One place for hosting & domains

      Como Instalar e Utilizar o TensorFlow no Ubuntu 18.04


      Introdução

      O TensorFlow é um software open-source de aprendizado de máquina ou machine learning usado para treinar redes neurais. As redes neurais do TensorFlow são expressas sob a forma de gráficos de fluxo de dados stateful. Cada nó no gráfico representa as operações realizadas por redes neurais em matrizes multidimensionais. Essas matrizes multidimensionais são comumente conhecidas como “tensores”, daí o nome TensorFlow.

      O TensorFlow é um sistema de software de deep learning. Ele funciona bem para a recuperação de informações, conforme demonstrado pelo Google na forma como eles pesquisam o ranking em seu sistema de inteligência artificial de machine learning, RankBrain. O TensorFlow pode realizar reconhecimento de imagem, conforme mostrado no Inception do Google, bem como reconhecimento de áudio em linguagem humana. Também é útil na resolução de outros problemas não específicos de machine learning, como equações diferenciais parciais.

      A arquitetura do TensorFlow permite o deployment em várias CPUs ou GPUs em um desktop, servidor ou dispositivo móvel. Existem também extensões para integração com CUDA, uma plataforma de computação paralela da Nvidia. Isso fornece aos usuários que estão fazendo deploy em uma GPU acesso direto ao conjunto de instruções virtuais e outros elementos da GPU que são necessários para tarefas computacionais paralelas.

      Neste tutorial, vamos instalar a versão “CPU support only” do TensorFlow. Essa instalação é ideal para pessoas que querem instalar e usar o TensorFlow, mas que não têm uma placa de vídeo Nvidia ou não precisam executar aplicações críticas em termos de desempenho.

      Você pode instalar o TensorFlow de várias maneiras. Cada método tem um caso de uso e um ambiente de desenvolvimento diferentes:

      • Python e Virtualenv: Nesta abordagem, você instala o TensorFlow e todos os pacotes necessários para utilizá-lo em um ambiente virtual do Python. Isso isola seu ambiente do TensorFlow de outros programas do Python na mesma máquina.
      • Native pip: Neste método, você instala o TensorFlow em seu sistema de maneira global. Isso é recomendado para pessoas que querem disponibilizar o TensorFlow para todos em um sistema multiusuário. Esse método de instalação não isola o TensorFlow em um ambiente de contenção e pode interferir em outras instalações ou bibliotecas do Python.
      • Docker: O Docker é um ambiente runtime de container e isola completamente seu conteúdo dos pacotes preexistentes em seu sistema. Nesse método, você usa um container do Docker que contém o TensorFlow e todas as suas dependências. Esse método é ideal para incorporar o TensorFlow a uma arquitetura de aplicações maior que já usa o Docker. No entanto, o tamanho da imagem do Docker será bem grande.

      Neste tutorial, você instalará o TensorFlow em um ambiente virtual do Python com virtualenv. Essa abordagem isola a instalação do TensorFlow e coloca tudo em funcionamento rapidamente. Depois de concluir a instalação, você fará a sua validação executando um pequeno programa do TensorFlow e, em seguida, utilizará o TensorFlow para realizar o reconhecimento de imagem.

      Pré-requisitos

      Antes de começar este tutorial, você precisará do seguinte:

      Passo 1 — Instalando o TensorFlow

      Nesta etapa, vamos criar um ambiente virtual e instalar o TensorFlow.

      Primeiro, crie um diretório de projeto. Vamos chamá-lo de tf-demo para fins de demonstração, mas escolha um nome de diretório que seja significativo para você:

      Navegue até o seu diretório tf-demo recém-criado:

      Em seguida, crie um novo ambiente virtual chamado tensorflow-dev, por exemplo. Execute o seguinte comando para criar o ambiente:

      • python3 -m venv tensorflow-dev

      Isto cria um novo diretório tensorflow-dev que conterá todos os pacotes que você instalar enquanto este ambiente estiver ativado. Também inclui o pip e uma versão independente do Python.

      Agora ative seu ambiente virtual:

      • source tensorflow-dev/bin/activate

      Uma vez ativado, você verá algo semelhante a isso no seu terminal:

      (tensorflow-dev)nome_de_usuário@hostname:~/tf-demo $
      

      Agora você pode instalar o TensorFlow em seu ambiente virtual.

      Execute o seguinte comando para instalar e atualizar para a versão mais recente do TensorFlow disponível em PyPi:

      • pip install --upgrade tensorflow

      O TensorFlow será instalado, e você deverá obter uma saída que indique que a instalação, juntamente com quaisquer pacotes dependentes, foi bem-sucedida.

      Output

      ... Successfully installed absl-py-0.7.1 astor-0.7.1 gast-0.2.2 grpcio-1.19.0 h5py-2.9.0 keras-applications-1.0.7 keras-preprocessing-1.0.9 markdown-3.0.1 mock-2.0.0 numpy-1.16.2 pbr-5.1.3 protobuf-3.7.0 setuptools-40.8.0 tensorboard-1.13.1 tensorflow-1.13.1 tensorflow-estimator-1.13.0 termcolor-1.1.0 werkzeug-0.15.0 wheel-0.33.1 ... Successfully installed bleach-1.5.0 enum34-1.1.6 html5lib-0.9999999 markdown-2.6.9 numpy-1.13.3 protobuf-3.5.0.post1 setuptools-38.2.3 six-1.11.0 tensorflow-1.4.0 tensorflow-tensorboard-0.4.0rc3 werkzeug-0.12.2 wheel-0.30.0

      Você pode desativar seu ambiente virtual a qualquer momento usando o seguinte comando:

      Para reativar o ambiente posteriormente, navegue até o diretório do projeto e execute source tensorflow-dev/bin/activate.

      Agora que você instalou o TensorFlow, vamos garantir que a instalação esteja funcionando.

      Passo 2 — Validando a Instalação

      Para validar a instalação do TensorFlow, vamos executar um programa simples como um usuário não-root. Usaremos o exemplo canônico de iniciante de "Hello, world!" como uma forma de validação. Em vez de criar um arquivo em Python, criaremos esse programa usando o console interativo do Python.

      Para escrever o programa, inicie seu interpretador Python:

      Você verá o seguinte prompt aparecer no seu terminal:

      >>>
      

      Este é o prompt do interpretador Python e indica que ele está pronto para que você comece a inserir algumas instruções do Python.

      Primeiro, digite esta linha para importar o pacote TensorFlow e disponibilizá-lo como a variável local tf. Pressione ENTER depois de digitar a linha de código:

      Em seguida, adicione esta linha de código para definir a mensagem "Hello, world!":

      • hello = tf.constant("Hello, world!")

      Em seguida, crie uma nova sessão do TensorFlow e atribua-a à variável sess:

      Nota: Dependendo do seu ambiente, você poderá ver esta saída:

      Output

      2019-03-20 16:22:45.956946: W tensorflow/core/platform/cpu_feature_guard.cc:45] The TensorFlow library wasn't compiled to use SSE4.1 instructions, but these are available on your machine and could speed up CPU computations. 2019-03-20 16:22:45.957158: W tensorflow/core/platform/cpu_feature_guard.cc:45] The TensorFlow library wasn't compiled to use SSE4.2 instructions, but these are available on your machine and could speed up CPU computations. 2019-03-20 16:22:45.957282: W tensorflow/core/platform/cpu_feature_guard.cc:45] The TensorFlow library wasn't compiled to use AVX instructions, but these are available on your machine and could speed up CPU computations. 2019-03-20 16:22:45.957404: W tensorflow/core/platform/cpu_feature_guard.cc:45] The TensorFlow library wasn't compiled to use AVX2 instructions, but these are available on your machine and could speed up CPU computations. 2019-03-20 16:22:45.957527: W tensorflow/core/platform/cpu_feature_guard.cc:45] The TensorFlow library wasn't compiled to use FMA instructions, but these are available on your machine and could speed up CPU computations.

      Isso lhe diz que você tem um conjunto de instruções que tem o potencial para ser otimizado para um melhor desempenho com o TensorFlow. Se você vir isso, poderá ignorar com segurança e continuar.

      Por fim, insira essa linha de código para imprimir o resultado da execução da sessão hello do TensorFlow que você construiu nas suas linhas de código anteriores:

      No Python 3, sess.run() irá retornar uma byte string, que será renderizada como b'Hello, world!' se você executar print(sess.run(hello)) sozinho. Para retornar Hello, world! como uma string, vamos adicionar o método decode().

      • print(sess.run(hello).decode())

      Você verá essa saída no seu console:

      Output

      Hello, world!

      Isso indica que tudo está funcionando e que você pode começar a usar o TensorFlow.

      Saia do console interativo do Python pressionando CTRL+D ou digitando quit().

      A seguir, vamos usar a API de reconhecimento de imagem do TensorFlow para nos familiarizarmos com o TensorFlow.

      Passo 3 — Usando o TensorFlow para Reconhecimento de Imagem

      Agora que o TensorFlow está instalado e você o validou executando um programa simples, podemos dar uma olhada em seus recursos de reconhecimento de imagem.

      Para classificar uma imagem, você precisa treinar um modelo. Então você precisa escrever algum código para usar o modelo. Para aprender mais sobre conceitos de machine learning, considere a leitura de “An Introduction to Machine Learning.”

      O TensorFlow fornece um repositório de modelos e exemplos, incluindo código e um modelo treinado para classificar imagens.

      Use o Git para clonar o repositório de modelos do TensorFlow do GitHub no diretório do seu projeto:

      • git clone https://github.com/tensorflow/models.git

      Você receberá a seguinte saída enquanto o Git clona o repositório em uma nova pasta chamada models:

      Output

      Cloning into 'models'... remote: Enumerating objects: 32, done. remote: Counting objects: 100% (32/32), done. remote: Compressing objects: 100% (26/26), done. remote: Total 24851 (delta 17), reused 12 (delta 6), pack-reused 24819 Receiving objects: 100% (24851/24851), 507.78 MiB | 32.73 MiB/s, done. Resolving deltas: 100% (14629/14629), done. Checking out files: 100% (2858/2858), done.

      Mude para o diretório models/tutorials/image/imagenet:

      • cd models/tutorials/image/imagenet

      Este diretório contém o arquivo classify_image.py que usa o TensorFlow para reconhecer imagens. Este programa faz o download de um modelo treinado a partir de tensorflow.org em sua primeira execução. O download desse modelo exige que você tenha 200 MB de espaço livre disponível no disco.

      Neste exemplo, vamos classificar uma imagem pré-fornecida de um Panda. Execute este comando para executar o programa classificador de imagens:

      Você receberá uma saída semelhante a esta:

      Output

      giant panda, panda, panda bear, coon bear, Ailuropoda melanoleuca (score = 0.89107) indri, indris, Indri indri, Indri brevicaudatus (score = 0.00779) lesser panda, red panda, panda, bear cat, cat bear, Ailurus fulgens (score = 0.00296) custard apple (score = 0.00147) earthstar (score = 0.00117)

      Você classificou sua primeira imagem usando os recursos de reconhecimento de imagem do TensorFlow.

      Se você quiser usar outra imagem, você pode fazer isso adicionando o argumento -- image_file ao seu comando python3 classify_image.py. Para o argumento, você passaria o caminho absoluto do arquivo de imagem.

      Conclusão

      Neste tutorial, você instalou o TensorFlow em um ambiente virtual do Python e validou o funcionamento do TensorFlow executando alguns exemplos. Agora você possui ferramentas que possibilitam a exploração de tópicos adicionais, incluindo Redes Neurais Convolucionais e Word Embeddings ou Vetores de Palavras.

      O guia do programador do TensorFlow fornece um recurso útil e uma referência para o desenvolvimento do TensorFlow. Você também pode explorar o Kaggle, um ambiente competitivo para a aplicação prática de conceitos de machine learning que o colocam contra outros entusiastas de machine learning, ciência de dados e estatística. Eles têm um wiki robusto onde você pode explorar e compartilhar soluções, algumas das quais estão na vanguarda das técnicas estatísticas e de machine learning.



      Source link

      Create and Deploy a Docker Container Image to a Kubernetes Cluster


      Updated by Linode Contributed by Linode

      Kubernetes and Docker

      Kubernetes is a system that automates the deployment, scaling, and management of containerized applications. Containerizing an application requires a base image that can be used to create an instance of a container. Once an application’s image exists, you can push it to a centralized container registry that Kubernetes can use to deploy container instances in a cluster’s pods.

      While Kubernetes supports several container runtimes, Docker is a very popular choice. Docker images are created using a Dockerfile that contains all commands, in their required order of execution, needed to build a given image. For example, a Dockerfile might contain instructions to install a specific operating system referencing another image, install an application’s dependencies, and execute configuration commands in the running container.

      Docker Hub is a centralized container image registry that can host your images and make them available for sharing and deployment. You can also find and use official Docker images and vendor specific images. When combined with a remote version control service, like GitHub, Docker Hub allows you to automate building container images and trigger actions for further automation with other services and tooling.

      Scope of This Guide

      This guide will show you how to package a Hugo static site in a Docker container image, host the image on Docker Hub, and deploy the container image on a Kubernetes cluster running on Linode. This example, is meant to demonstrate how applications can be containerized using Docker to leverage the deployment and scaling power of Kubernetes.

      Hugo is written in Go and is known for being extremely fast to compile sites, even very large ones. It is well-supported, well-documented, and has an active community. Some useful Hugo features include shortcodes, which are an easy way to include predefined templates inside of your Markdown, and built-in LiveReload web server, which allows you to preview your site changes locally as you make them.

      Note

      This guide was written using version 1.14 of Kubectl.

      Before You Begin

      1. Create a Kubernetes cluster with one worker node. This can be done in two ways:

        1. Deploy a Kubernetes cluster using kubeadm.
          • You will need to deploy two Linodes. One will serve as the master node and the other will serve as a worker node.
        2. Deploy a Kubernetes cluster using k8s-alpha CLI.
      2. Create a GitHub account if you don’t already have one.

      3. Create a Docker Hub account if you don’t already have one.

      Set up the Development Environment

      Development of your Hugo site and Docker image will take place locally on your personal computer. You will need to install Hugo, Docker CE, and Git, a version control software, on your personal computer to get started.

      1. Use the How to Install Git on Linux, Mac or Windows guide for the steps needed to install Git.

      2. Install Hugo. Hugo’s official documentation contains more information on installation methods, like Installing Hugo from Tarball. Below are installation instructions for common operating systems:

        • Debian/Ubuntu:

          sudo apt-get install hugo
          
        • Fedora, Red Hat and CentOS:

          sudo dnf install hugo
          
        • Mac, using Homebrew:

          brew install hugo
          
      3. These steps install Docker Community Edition (CE) using the official Ubuntu repositories. To install on another distribution, see the official installation page.

        1. Remove any older installations of Docker that may be on your system:

          sudo apt remove docker docker-engine docker.io
          
        2. Make sure you have the necessary packages to allow the use of Docker’s repository:

          sudo apt install apt-transport-https ca-certificates curl software-properties-common
          
        3. Add Docker’s GPG key:

          curl -fsSL https://download.docker.com/linux/ubuntu/gpg | sudo apt-key add -
          
        4. Verify the fingerprint of the GPG key:

          sudo apt-key fingerprint 0EBFCD88
          

          You should see output similar to the following:

            
          pub   4096R/0EBFCD88 2017-02-22
                  Key fingerprint = 9DC8 5822 9FC7 DD38 854A  E2D8 8D81 803C 0EBF CD88
          uid                  Docker Release (CE deb) 
          sub   4096R/F273FCD8 2017-02-22
          
          
        5. Add the stable Docker repository:

          sudo add-apt-repository "deb [arch=amd64] https://download.docker.com/linux/ubuntu $(lsb_release -cs) stable"
          
        6. Update your package index and install Docker CE:

          sudo apt update
          sudo apt install docker-ce
          
        7. Add your limited Linux user account to the docker group:

          sudo usermod -aG docker $USER
          

          Note

          After entering the usermod command, you will need to close your SSH session and open a new one for this change to take effect.

        8. Check that the installation was successful by running the built-in “Hello World” program:

          docker run hello-world
          

      Create a Hugo Site

      Initialize the Hugo Site

      In this section you will use the Hugo CLI (command line interface) to create your Hugo site and initialize a Hugo theme. Hugo’s CLI provides several useful commands for common tasks needed to build, configure, and interact with your Hugo site.

      1. Create a new Hugo site on your local computer. This command will create a folder named example-site and scaffold Hugo’s directory structure inside it:

        hugo new site example-site
        
      2. Move into your Hugo site’s root directory:

        cd example-site
        
      3. You will use Git to add a theme to your Hugo site’s directory. Initialize your Hugo site’s directory as a Git repository:

        git init
        
      4. Install the Ananke theme as a submodule of your Hugo site’s Git repository. Git submodules allow one Git repository to be stored as a subdirectory of another Git repository, while still being able to maintain each repository’s version control information separately. The Ananke theme’s repository will be located in the ~/example-site/themes/ananke directory of your Hugo site.

        git submodule add https://github.com/budparr/gohugo-theme-ananke.git themes/ananke
        

        Note

        Hugo has many available themes that can be installed as a submodule of your Hugo site’s directory.
      5. Add the theme to your Hugo site’s configuration file. The configuration file (config.toml) is located at the root of your Hugo site’s directory.

        echo 'theme = "ananke"' >> config.toml
        

      Add Content to the Hugo Site

      You can now begin to add content to your Hugo site. In this section you will add a new post to your Hugo site and generate the corresponding static file by building the Hugo site on your local computer.

      1. Create a new content file for your site. This command will generate a Markdown file with an auto-populated date and title:

        hugo new posts/my-first-post.md
        
      2. You should see a similar output. Note that the file is located in the content/posts/ directory of your Hugo site:

          
        /home/username/example-site/content/posts/my-first-post.md created
            
        
      3. Open the Markdown file in the text editor of your choice to begin modifying its content; you can copy and paste the example snippet into your file, which contains an updated front matter section at the top and some example Markdown body text.

        Set your desired value for title. Then, set the draft state to false and add your content below the --- in Markdown syntax, if desired:

        /home/username/example-site/content/posts/my-first-post.md
         1
         2
         3
         4
         5
         6
         7
         8
         9
        10
        11
        12
        13
        
        ---
        title: "My First Post"
        date: 2019-05-07T11:25:11-04:00
        draft: false
        ---
        
        # Kubernetes Objects
        
        In Kubernetes, there are a number of objects that are abstractions of your Kubernetes system’s desired state. These objects represent your application, its networking, and disk resources – all of which together form your application. Kubernetes objects can describe:
        
        - Which containerized applications are running on the cluster
        - Application resources
        - Policies that should be applied to the application

        About front matter

        Front matter is a collection of metadata about your content, and it is embedded at the top of your file within opening and closing --- delimiters.

        Front matter is a powerful Hugo feature that provides a mechanism for passing data that is attached to a specific piece of content to Hugo’s rendering engine. Hugo accepts front matter in TOML, YAML, and JSON formats. In the example snippet, there is YAML front matter for the title, date, and draft state of the Markdown file. These variables will be referenced and displayed by your Hugo theme.

      4. Once you have added your content, you can preview your changes by building and serving the site using Hugo’s built-in webserver:

        hugo server
        
      5. You will see a similar output:

          
        &nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp| EN
        +------------------+----+
          Pages&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp| 11
          Paginator pages&nbsp&nbsp&nbsp&nbsp|  0
          Non-page files&nbsp&nbsp&nbsp&nbsp&nbsp|  0
          Static files&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp|  3
          Processed images&nbsp&nbsp&nbsp|  0
          Aliases&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp|  1
          Sitemaps&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp|  1
          Cleaned&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp|  0
        
        Total in 7 ms
        Watching for changes in /home/username/example-site/{content,data,layouts,static,themes}
        Watching for config changes in /home/username/example-site/config.toml
        Serving pages from memory
        Running in Fast Render Mode. For full rebuilds on change: hugo server --disableFastRender
        Web Server is available at http://localhost:1313/ (bind address 127.0.0.1)
        Press Ctrl+C to stop
        
        
      6. The output will provide a URL to preview your site. Copy and paste the URL into a browser to access the site. In the above example Hugo’s web server URL is http://localhost:1313/.

      7. When you are happy with your site’s content you can build the site:

        hugo -v
        

        Hugo will generate your site’s static HTML files and store them in a public directory that it will create inside your project. The static files that are generated by Hugo are the files that will be served to the internet through your Kubernetes cluster.

      8. View the contents of your site’s public directory:

        ls public
        

        Your output should resemble the following example. When you built the site, the Markdown file you created and edited in steps 6 and 7 was used to generate its corresponding static HTML file in the public/posts/my-first-post/index.html directory.

          
          404.html    categories  dist        images      index.html  index.xml   posts       sitemap.xml tags
            
        

      Version Control the Site with Git

      The example Hugo site was initialized as a local Git repository in the previous section. You can now version control all content, theme, and configuration files with Git. Once you have used Git to track your local Hugo site files, you can easily push them to a remote Git repository, like GitHub or GitLab. Storing your Hugo site files on a remote Git repository opens up many possibilities for collaboration and automating Docker image builds. This guide will not cover automated builds, but you can learn more about it on Docker’s official documentation.

      1. Add a .gitignore file to your Git repository. Any files or directories added to the .gitignore file will not be tracked by Git. The Docker image you will create in the next section will handle building your static site files. For this reason it is not necessary to track the public directory and its content.

        echo 'public/' >> .gitignore
        
      2. Display the state of your current working directory (root of your Hugo site):

        git status
        
      3. Stage all your files to be committed:

        git add -A
        
      4. Commit all your changes and add a meaningful commit message:

        git commit -m 'Add content, theme, and config files.'
        

        Note

        Any time you complete work related to one logical change to the Hugo site, you should make sure you commit the changes to your Git repository. Keeping your commits attached to small changes makes it easier to understand the changes and to roll back to previous commits, if necessary. See the Getting Started with Git guide for more information.

      Create a Docker Image

      Create the Dockerfile

      A Dockerfile contains the steps needed to build a Docker image. The Docker image provides the minimum set up and configuration necessary to deploy a container that satisfies its specific use case. The Hugo site’s minimum Docker container configuration requirements are an operating system, Hugo, the Hugo site’s content files, and the NGINX web server.

      1. In your Hugo site’s root directory, create and open a file named Dockerfile using the text editor of your choice. Add the following content to the file. You can read the Dockerfile comments to learn what each command will execute in the Docker container.

        Dockerfile
         1
         2
         3
         4
         5
         6
         7
         8
         9
        10
        11
        12
        13
        14
        15
        16
        17
        18
        19
        20
        21
        22
        23
        24
        
        #Install the container's OS.
        FROM ubuntu:latest as HUGOINSTALL
        
        # Install Hugo.
        RUN apt-get update
        RUN apt-get install hugo
        
        # Copy the contents of the current working directory to the hugo-site
        # directory. The directory will be created if it doesn't exist.
        COPY . /hugo-site
        
        # Use Hugo to build the static site files.
        RUN hugo -v --source=/hugo-site --destination=/hugo-site/public
        
        # Install NGINX and deactivate NGINX's default index.html file.
        # Move the static site files to NGINX's html directory.
        # This directory is where the static site files will be served from by NGINX.
        FROM nginx:stable-alpine
        RUN mv /usr/share/nginx/html/index.html /usr/share/nginx/html/old-index.html
        COPY --from=HUGOINSTALL /hugo-site/public/ /usr/share/nginx/html/
        
        # The container will listen on port 80 using the TCP protocol.
        EXPOSE 80
            
      2. Add a .dockerignore file to your Hugo repository. It is important to ensure that your images are as small as possible to reduce the time it takes to build, pull, push, and deploy the container. The .dockerignore file excludes files and directories that are not necessary for the function of your container or that may contain sensitive information that you do not want to included in the image. Since the Docker image will build the static Hugo site files, you can ignore the public/ directory. You can also exclude any Git related files and directories because they are not needed on the running container.

        echo -e "public/n.git/n.gitmodules/n.gitignore" >> .dockerignore
        
      3. Follow the steps 2 – 4 in the Version Control the Site with Git section to add any new files created in this section to your local git repository.

      Build the Docker Image

      You are now ready to build the Docker image. When Docker builds an image it incorporates the build context. A build context includes any files and directories located in the current working directory. By default, Docker assumes the current working directory is also the location of the Dockerfile.

      Note

      If you have not yet created a Docker Hub account, you will need to do so before proceeding with this section.
      1. Build the Docker image and add a tag mydockerhubusername/hugo-site:v1 to the image. Ensure you are in the root directory of your Hugo site. The tag will make it easy to reference a specific image version when creating your Kubernetes deployment manifest. Replace mydockerhubusername with your Docker Hub username and hugo-site with a Docker repository name you prefer.

        docker build -t mydockerhubusername/hugo-site:v1 .
        

        You should see a similar output. The entirety of the output has been removed for brevity:

          
        Sending build context to Docker daemon  3.307MB
        Step 1/10 : FROM ubuntu:latest as HUGOINSTALL
         ---> 94e814e2efa8
        Step 2/10 : ENV HUGO_VERSION=0.55.4
         ---> Using cache
         ---> e651df397e32
         ...
        
        Successfully built 50c590837916
        Successfully tagged hugo-k8s:v1
            
        
      2. View all locally available Docker images:

        docker images
        

        You should see the docker image hugo-site:v1 listed in the output:

          
        REPOSITORY          TAG                 IMAGE ID            CREATED             SIZE
        hugo-k8s            v1                  50c590837916        1 day ago          16.5MB
            
        

      Push your Hugo Site Repository to GitHub

      You can push your local Hugo site’s Git repository to GitHub in order to set up Docker automated builds. Docker automated builds will build an image using a external repository as the build context and automatically push the image to your Docker Hub repository. This step is not necessary to complete this guide.

      Host your Image on Docker Hub

      Hosting your Hugo site’s image on Docker Hub will enable you to use the image in a Kubernetes cluster deployment. You will also be able to share the image with collaborators and the rest of the Docker community.

      1. Log into your Docker Hub account via the command line on your local computer. Enter your username and password when prompted.

        docker login
        
      2. Push the local Docker image to Docker Hub. Replace mydockerhubusername/hugo-site:v1 with your image’s tag name.

        docker push mydockerhubusername/hugo-site:v1
        
      3. Navigate to Docker Hub to view your image on your account.

        The url for your image repository should be similar to the following: https://cloud.docker.com/repository/docker/mydockerhubusername/hugo-site. Replace the username and repository name with your own.

      Configure your Kubernetes Cluster

      This section will use kubectl to configure and manage your Kubernetes cluster. If your cluster was deployed using kubeadm, you will need to log into your master node to execute the kubectl commands in this section. If, instead, you used the k8s-alpha CLI you can run all commands from your local computer.

      In this section, you will create namespace, deployment, and service manifest files for your Hugo site deployment and apply them to your cluster with kubectl. Each manifest file creates different resources on the Kubernetes API that are used to create and the Hugo site’s pods on the worker nodes.

      Create the Namespace

      Namespaces provide a powerful way to logically partition your Kubernetes cluster and isolate components and resources to avoid collisions across the cluster. A common use-case is to encapsulate dev/testing/production environments with namespaces so that they can each utilize the same resource names across each stage of development.

      Namespaces add a layer of complexity to a cluster that may not always be necessary. It is important to keep this in mind when formulating the architecture for a project’s application. This example will create a namespace for demonstration purposes, but it is not a requirement. One situation where a namespace would be beneficial, in the context of this guide, would be if you were a developer and wanted to manage Hugo sites for several clients with a single Kubernetes cluster.

      1. Create a directory to store your Hugo site’s manifest files.

        mkdir -p clientx/k8s-hugo/
        
      2. Create the manifest file for your Hugo site’s namespace with the following content:

        clientx/k8s-hugo/ns-hugo-site.yaml
        1
        2
        3
        4
        5
        
        apiVersion: v1
        kind: Namespace
        metadata:
          name: hugo-site
              
        • The manifest file declares the version of the API in use, the kind of resource that is being defined, and metadata about the resource. All manifest files should provide this information.
        • The key-value pair name: hugo-site defines the namespace object’s unique name.
      3. Create the namespace from the ns-hugo-site.yaml manifest.

        kubectl create -f clientx/k8s-hugo/ns-hugo-site.yaml
        
      4. View all available namespaces in your cluster:

        kubectl get namespaces
        

        You should see the hugo-site namespace listed in the output:

          
        NAME          STATUS   AGE
        default       Active   1d
        hugo-site     Active   1d
        kube-public   Active   1d
        kube-system   Active   1d
            
        

      Create the Service

      The service will group together all pods for the Hugo site, expose the same port on all pods to the internet, and load balance site traffic between all pods. It is best to create a service prior to any controllers (like a deployment) so that the Kubernetes scheduler can distribute the pods for the service as they are created by the controller.

      The Hugo site’s service manifest file will use the NodePort method to get external traffic to the Hugo site service. NodePort opens a specific port on all the Nodes and any traffic that is sent to this port is forwarded to the service. Kubernetes will choose the port to open on the nodes if you do not provide one in your service manifest file. It is recommended to let Kubernetes handle the assignment. Kubernetes will choose a port in the default range, 30000-32767.

      Note

      The k8s-alpha CLI creates clusters that are pre-configured with useful Linode service integrations, like the Linode Cloud Controller Manager (CCM) which provides access to Linode’s load balancer service, NodeBalancers. In order to use Linode’s NodeBalancers you can use the LoadBalancer service type instead of NodePort in your Hugo site’s service manifest file. For more details, see the Kubernetes Cloud Controller Manager for Linode GitHub repository.
      1. Create the manifest file for your service with the following content.

        clientx/k8s-hugo/service-hugo.yaml
         1
         2
         3
         4
         5
         6
         7
         8
         9
        10
        11
        12
        13
        14
        
        apiVersion: v1
        kind: Service
        metadata:
          name: : hugo-site
          namespace: hugo-site
        spec:
          selector:
            app: hugo-site
          ports:
          - protocol: TCP
            port: 80
            targetPort: 80
          type: NodePort
            
        • The spec key defines the Hugo site service object’s desired behavior. It will create a service that exposes TCP port 80 on any pod with the app: hugo-site label.
        • The exposed container port is defined by the targetPort:80 key-value pair.
      2. Create the service for your hugo site:

        kubectl create -f clientx/k8s-hugo/service-hugo.yaml
        
      3. View the service and its corresponding information:

        kubectl get services -n hugo-site
        

        Your output will resemble the following:

          
        NAME        TYPE       CLUSTER-IP     EXTERNAL-IP   PORT(S)        AGE
        hugo-site   NodePort   10.108.110.6           80:30304/TCP   1d
            
        

      Create the Deployment

      A deployment is a controller that helps manage the state of your pods. The Hugo site deployment will define how many pods should be kept up and running with the Hugo site service and which container image should be used.

      1. Create the manifest file for your Hugo site’s deployment. Copy the following contents to your file.

        clientx/k8s-hugo/deployment.yaml
         1
         2
         3
         4
         5
         6
         7
         8
         9
        10
        11
        12
        13
        14
        15
        16
        17
        18
        19
        20
        21
        22
        
        apiVersion: apps/v1
        kind: Deployment
        metadata:
          name: hugo-site
          namespace: hugo-site
        spec:
          replicas: 3
          selector:
            matchLabels:
              app: hugo-site
          template:
            metadata:
              labels:
                app: hugo-site
            spec:
              containers:
              - name: hugo-site
                image: mydockerhubusername/hugo-site:v1
                imagePullPolicy: Always
                ports:
                - containerPort: 80
              
        • The deployment’s object spec states that the deployment should have 3 replica pods. This means at any given time the cluster will have 3 pods that run the Hugo site service.
        • The template field provides all the information needed to create actual pods.
        • The label app: hugo-site helps the deployment know which service pods to target.
        • The container field states that any containers connected to this deployment should use the Hugo site image mydockerhubusername/hugo-site:v1 that was created in the Build the Docker Image section of this guide.
        • imagePullPolicy: Always means that the container image will be pulled every time the pod is started.
        • containerPort: 80 states the port number to expose on the pod’s IP address. The system does not rely on this field to expose the container port, instead, it provides information about the network connections a container uses.
      2. Create the deployment for your hugo site:

        kubectl create -f clientx/k8s-hugo/deployment.yaml
        
      3. View the Hugo site’s deployment:

        kubectl get deployment hugo-site -n hugo-site
        

        Your output will resemble the following:

          
        NAME        READY   UP-TO-DATE   AVAILABLE   AGE
        hugo-site   3/3     3            3           1d
            
        

      View the Hugo Site

      After creating all required manifest files to configure your Hugo site’s Kubernetes cluster, you should be able to view the site using a worker node’s IP address and its exposed port.

      1. Get your worker node’s external IP address. Copy down the EXTERNAL-IP value for any worker node in the cluster:

        kubectl get nodes -o wide
        
      2. Access the hugo-site services to view its exposed port.

        kubectl get svc -n hugo-site
        

        The output will resemble the following. Copy down the listed port number in the 30000-32767 range.

          
        NAME        TYPE       CLUSTER-IP     EXTERNAL-IP   PORT(S)        AGE
        hugo-site   NodePort   10.108.110.6           80:30304/TCP   1d
            
        
      3. Open a browser window and enter in a worker node’s IP address and exposed port. An example url to your Hugo site would be, http://192.0.2.1:30304. Your Hugo site should appear.

        If desired, you can purchase a domain name and use Linode’s DNS Manager to assign a domain name to the cluster’s worker node IP address.

      Tear Down Your Cluster

      To avoid being further billed for your Kubernetes cluster, tear down your cluster’s Linodes. If you have Linodes that existed for only part a monthly billing cycle, you’ll be billed at the hourly rate for that service. See How Hourly Billing Works to learn more.

      Next Steps

      Now that you are familiar with basic Kubernetes concepts, like configuring pods, grouping resources, and deploying services, you can deploy a Kubernetes cluster on Linode for production use by using the steps in the following guides:

      More Information

      You may wish to consult the following resources for additional information on this topic. While these are provided in the hope that they will be useful, please note that we cannot vouch for the accuracy or timeliness of externally hosted materials.

      Find answers, ask questions, and help others.

      This guide is published under a CC BY-ND 4.0 license.



      Source link

      Como Instalar o Java com `apt` no Ubuntu 18.04


      O autor selecionou o Open Internet/Free Speech Fund para receber uma doação de $100 como parte do programa Escreva para DOações.

      Introdução

      Java e a JVM (Java’s virtual machine) são necessários para utilizar vários tipos de software, incluindo o Tomcat, Jetty, Glassfish, Cassandra e Jenkins.

      Neste guia, você irá instalar várias versões do Java Runtime Environment (JRE) e do Java Developer Kit (JDK) utilizando o apt. Você irá instalar o OpenJDK e também os pacotes oficiais da Oracle. Em seguida, você irá selecionar a versão que você deseja utilizar em seus projetos. Quando você finalizar o guia, você será capaz de utilizar o JDK para desenvolver seus programas ou utilizar o Java Runtime para rodar seus programas.

      Pré-requisitos

      Para seguir ester tutorial, você precisará de:

      Instalando o JRE/JDK Padrão

      A opção mais fácil para instalar o Java é utilizando o pacote que vem com o Ubuntu. Por padrão, o Ubuntu 18.04 inclui o OpenJDK, que é a alternativa open-source do JRE e JDK.

      Esse pacote irá instalar ou o OpenJDK 10 ou o 11.

      • Antes de Setembro de 2018, ele irá instalar o OpenJDK 10.
      • Depois de Setembro de 2018, ele irá instalar o OpenJDK 11.

      Para instalar essa versão, primeiro precisamos atualizar a lista de pacotes do apt:

      Depois, checar se o Java já está instalado:

      Se o Java não estiver instalado, você verá a seguinte mensagem:

      Output

      Command 'java' not found, but can be installed with: apt install default-jre apt install openjdk-11-jre-headless apt install openjdk-8-jre-headless

      Execute o seguinte comando para instalar o OpenJDK:

      • sudo apt install default-jre

      Esse comando irá instalar o Java Runtime Environment (JRE). Isso vai permitir que você execute praticamente todos os programas em Java.

      Verifique a instalação com:

      Você verá a seguinte mensagem:

      Output

      openjdk version "10.0.2" 2018-07-17 OpenJDK Runtime Environment (build 10.0.2+13-Ubuntu-1ubuntu0.18.04.4) OpenJDK 64-Bit Server VM (build 10.0.2+13-Ubuntu-1ubuntu0.18.04.4, mixed mode)

      Você talvez precise do Java Development Kit (JDK) junto do JRE para poder compilar e rodar algum programa específico em Java. Para instalar o JDK, execute os seguintes comandos, que também irão instalar o JRE:

      • sudo apt install default-jdk

      Verifique se o JDK foi instalado checando a versão do javac, o compilador Java:

      Você verá a seguinte mensagem:

      Output

      javac 10.0.2

      A seguir, veremos como especificar uma versão do OpenJDK que nós queremos instalar.

      Instalando uma versão especifica do OpenJDK

      OpenJDK 8

      Java 8 é a versão Long Term Support (Suporte de longo prazo) atual e ainda é amplamente suportada, apesar da manutenção pública terminar em Janeiro de 2019. Para instalar o OpenJDK 8, execute o seguinte comando:

      • sudo apt install openjdk-8-jdk

      Verifique se foi instalado com:

      Você verá a seguinte mensagem:

      Output

      openjdk version "1.8.0_191" OpenJDK Runtime Environment (build 1.8.0_191-8u191-b12-2ubuntu0.18.04.1-b12) OpenJDK 64-Bit Server VM (build 25.191-b12, mixed mode)

      Também é possível instalar somente o JRE, o que você pode fazer executando o seguinte comando sudo apt install openjdk-8-jre.

      OpenJDK 10/11

      Os repositórios do Ubuntu possuem os pacotes que instalarão o Java 10 ou o 11. Até Setembro de 2018, esse pacote irá instalar o OpenJDK 10. Assim que o Java 11 for lançado, esse pacote instalará o Java 11.

      Para instalar o OpenJDK 10/10, execute o seguinte comando:

      • sudo apt install openjdk-11-jdk

      Para instalar somente o JRE, use o seguinte comando:

      • sudo apt install openjdk-11-jre

      A seguir, vamos ver como instalar o JDK e o JRE oficiais da Oracle.

      Instalando o Oracle JDK

      Se quiser instalar o Oracle JDK, que é a versão oficial distribuída pela Oracle, você precisará adicionar um novo repositório de pacotes para a versão que você gostaria de instalar.

      Para instalar o Java 8, que é a última versão LTS, primeiramente adicione o repositório do pacote:

      • sudo add-apt-repository ppa:webupd8team/java

      Quando você adicionar o repositório, você verá uma mensagem parecida com essa:

      output

      Oracle Java (JDK) Installer (automatically downloads and installs Oracle JDK8). There are no actual Java files in this PPA. Important -> Why Oracle Java 7 And 6 Installers No Longer Work: http://www.webupd8.org/2017/06/why-oracle-java-7-and-6-installers-no.html Update: Oracle Java 9 has reached end of life: http://www.oracle.com/technetwork/java/javase/downloads/jdk9-downloads-3848520.html The PPA supports Ubuntu 18.10, 18.04, 16.04, 14.04 and 12.04. More info (and Ubuntu installation instructions): - http://www.webupd8.org/2012/09/install-oracle-java-8-in-ubuntu-via-ppa.html Debian installation instructions: - Oracle Java 8: http://www.webupd8.org/2014/03/how-to-install-oracle-java-8-in-debian.html For Oracle Java 11, see a different PPA -> https://www.linuxuprising.com/2018/10/how-to-install-oracle-java-11-in-ubuntu.html More info: https://launchpad.net/~webupd8team/+archive/ubuntu/java Press [ENTER] to continue or Ctrl-c to cancel adding it.

      Pressione ENTER para continuar. Depois atualize sua lista de pacotes:

      Quando a lista de pacotes atualizar, instale o Java 8:

      • sudo apt install oracle-java8-installer

      Seu sistema irá realizar o download do JDK da Oracle e irá solicitar que você aceite os termos de licença. Aceite os termos e o JDK será instalado.

      Agora vamos ver como selecionar qual versão do Java você deseja utilizar.

      Gerenciando o Java

      Você pode ter múltiplas instalações do Java em um servidor. Você pode configurar qual versão será utilizada por padrão no terminal, usando o comando update-alternatives.

      • sudo update-alternatives --config java

      Será assim que a saída vai parecer se você instalou todas as versões de Java desse tutorial:

      Output

      There are 3 choices for the alternative java (providing /usr/bin/java). Selection Path Priority Status ------------------------------------------------------------ * 0 /usr/lib/jvm/java-11-openjdk-amd64/bin/java 1101 auto mode 1 /usr/lib/jvm/java-11-openjdk-amd64/bin/java 1101 manual mode 2 /usr/lib/jvm/java-8-openjdk-amd64/jre/bin/java 1081 manual mode 3 /usr/lib/jvm/java-8-oracle/jre/bin/java 1081 manual mode

      Escolha o número que está associado com a versão do Java que será utilizada como padrão, ou pressione ENTER para deixar a configuração atual no lugar.

      Você pode usar isso para outros comandos Java, como o compilador (javac):

      • sudo update-alternatives --config javac

      Outros comandos para os quais esse comando pode ser utilizado incluem, mas não ficam limitados a: keytool, javadoc e jarsigner.

      Configurando a Variavel de Ambiente JAVA_HOME

      Muitos programas escritos em Java, utilizam a variável de ambiente JAVA_HOME para determinar o local de instalação do Java.

      Para configurar esta variável de ambiente, primeiramente defina onde o Java está instalado. Utilize o comando update-alternatives:

      • sudo update-alternatives --config java

      Esse comando mostra cada instalação do Java junto com seu caminho de instalação:

      Output

      There are 3 choices for the alternative java (providing /usr/bin/java). Selection Path Priority Status ------------------------------------------------------------ * 0 /usr/lib/jvm/java-11-openjdk-amd64/bin/java 1101 auto mode 1 /usr/lib/jvm/java-11-openjdk-amd64/bin/java 1101 manual mode 2 /usr/lib/jvm/java-8-openjdk-amd64/jre/bin/java 1081 manual mode 3 /usr/lib/jvm/java-8-oracle/jre/bin/java 1081 manual mode Press <enter> to keep the current choice[*], or type selection number:

      Nesse caso, os caminhos de instalação são os seguintes:

      1. OpenJDK 11 está localizado em /usr/lib/jvm/java-11-openjdk-amd64/bin/java.
      2. OpenJDK 8 está localizado em /usr/lib/jvm/java-8-openjdk-amd64/jre/bin/java.
      3. Oracle Java 8 está localizado em /usr/lib/jvm/java-8-oracle/jre/bin/java.

      Copie o caminho da instalação que você deseja utilizar. Depois abra /etc/environment utilizando o nano ou o seu editor de texto favorito:

      • sudo nano /etc/environment

      No final desse arquivo, adicione a seguinte linha, certificando-se de substituir o caminho destacado com o que você copiou do seu sistema:

      /etc/environment

      JAVA_HOME="/usr/lib/jvm/java-11-openjdk-amd64/bin/"
      

      Ao modificar esse arquivo você irá configurar o caminho JAVA_HOME para todos os usuários do seu sistema.

      Salve o arquivo e saia do editor de texto.

      Agora recarregue arquivo para aplicar as mudanças para sua sessão atual:

      Verifique se a sua variável de ambiente foi configurada:

      Você verá o caminho que você acabou de configurar:

      Output

      /usr/lib/jvm/java-11-openjdk-amd64/bin/

      Os outros usuários precisaram executar o comando source /etc/environment ou desconectar e logar novamente para aplicar essa configuração.

      Conclusão

      Nesse tutorial você instalou múltiplas versões do Java e aprendeu como gerenciá-las. Você agora pode instalar os programas que rodam em Java, tais como o Tomcat, Jetty, Glassfish, Cassandra ou Jenkins.



      Source link