One place for hosting & domains

      Como Criar um Cluster Kubernetes 1.11 Usando Kubeadm no Ubuntu 18.04


      O autor escolheu o Free and Open Source Fund para receber uma doação como parte do programa Write for DOnations.

      Introdução

      O Kubernetes é um sistema de orquestração de container em escala. Inicialmente desenvolvido pelo Google baseado em suas experiências executando containers em produção. O Kubernetes é open source e desenvolvido ativamente por uma comunidade em todo o mundo.

      O Kubeadm atomatiza a instalação e a configuração de componentes do Kubernetes tais como o servidor de API, o Controller Manager, e o Kube DNS. Contudo, ele não cria usuários ou lida com a instalação de dependências no nível do sistema operacional e sua configuração. Para essa tarefas preliminares, é possível utilizar uma ferramenta de gerência de configuração como o Ansible ou o SaltStack. A utilização dessas ferramentas torna a criação de clusters adicionais ou a recriação de clusters existentes muito mais simples e menos propensa a erros.

      Neste guia, você vai configurar um cluster Kubernetes a partir do zero utilizando o Ansible e o Kubeadm, e a seguir fazer o deploy de uma aplicação Nginx containerizada nele.

      Objetivos

      Seu cluster irá incluir os seguintes recursos físicos:

      O node master (um node no Kubernetes refere-se a um servidor) é responsável por gerenciar o estado do cluster. Ele roda o Etcd, que armazena dados de cluster entre componentes que fazem o scheduling de cargas de trabalho para nodes worker ou nodes de trabalho.

      Nodes worker são os servidores onde suas cargas de trabalho (i.e. aplicações e serviços containerizados) irão executar. Um worker continuará a executar sua carga de trabalho uma vez que estejam atribuídos a ela, mesmo se o master for desativado quando o scheduling estiver concluído. A capacidade de um cluster pode ser aumentada adicionando workers.

      Após a conclusão desse guia, você terá um cluster pronto para executar aplicações containerizadas, desde que os servidores no cluster tenham recursos suficientes de CPU e RAM para suas aplicações consumirem. Quase todas as aplicações Unix tradicionais, incluindo aplicações web, bancos de dados, daemons, e ferramentas de linha de comando podem ser containerizadas e feitas para rodar no cluster. O cluster em si consumirá cerca de 300-500MB de memória e 10% de CPU em cada node.

      Uma vez que o cluster esteja configurado, você fará o deploy do servidor web Nginx nele para assegurar que ele está executando as cargas de trabalho corretamente.

      Pré-requisitos

      Passo 1 — Configurando o Diretório da Área de Trabalho e o Arquivo de Inventário Ansible

      Nessa seção, você vai criar um diretório em sua máquina local que irá servir como sua área de trabalho. Você configurará o Ansible localmente para que ele possa se comunicar e executar comandos em seus servidores remotos. Depois disso pronto, você irá criar um arquivo hosts contendo informações de inventário tais como os endereços IP de seus servidores e os grupos aos quais cada servidor pertence.

      Dos seus três servidores, um será o master com um IP exibido como master_ip. Os outros dois servidores serão workers e terão os IPs worker_1_ip e worker_2_ip.

      Crie um diretório chamado ~/kube-cluster no diretório home de sua máquina local e faça um cd para dentro dele:

      • mkdir ~/kube-cluster
      • cd ~/kube-cluster

      Esse diretório será sua área de trabalho para o restante desse tutorial e conterá todos os seus playbooks de Ansible. Ele também será o diretório no qual você irá executar todos os comandos locais.

      Crie um arquivo chamado ~/kube-cluster/hosts usando o nano ou o seu editor de textos favorito:

      • nano ~/kube-cluster/hosts

      Adicione o seguinte texto ao arquivo, que irá especificar informações sobre a estrutura lógica do cluster:

      ~/kube-cluster/hosts

      
      [masters]
      master ansible_host=master_ip ansible_user=root
      
      [workers]
      worker1 ansible_host=worker_1_ip ansible_user=root
      worker2 ansible_host=worker_2_ip ansible_user=root
      
      [all:vars]
      ansible_python_interpreter=/usr/bin/python3
      

      Você deve se lembrar de que arquivos de inventário no Ansible são utilizados para especificar informações de servidor tais como endereços IP, usuários remotos, e agrupamentos de servidores para tratar como uma unidade única para a execução de comandos. O ~/kube-cluster/hosts será o seu arquivo de inventário e você adicionou dois grupos Ansible a ele (masters e workers) especificando a estrutura lógica do seu cluster.

      No grupo masters, existe uma entrada de servidor chamada “master” que lista o IP do node master (master_ip) e especifica que o Ansible deve executar comandos remotos como root.

      De maneira similar, no grupo workers, existem duas entradas para os servidores workers (worker_1_ip e worker_2_ip) que também especificam o ansible_user como root.

      A última linha do arquivo diz ao Ansible para utilizar os intepretadores Python dos servidores remotos para suas operações de gerenciamento.

      Salve e feche o arquivo depois de ter adicionado o texto.

      Tendo configurado o inventário do servidor com grupos, vamos passar a instalar dependências no nível do sistema operacional e a criar definições de configuração.

      Passo 2 — Criando um Usuário Não-Root em Todos os Servidores Remotos

      Nesta seção você irá criar um usuário não-root com privilégios sudo em todos os servidores para que você possa fazer SSH manualmente neles como um usuário sem privilégios. Isso pode ser útil se, por exemplo, você gostaria de ver informações do sistema com comandos como top/htop, ver a lista de containers em execução, ou alterar arquivos de configuração de propriedade do root. Estas operações são rotineiramente executadas durante a manutenção de um cluster, e a utilização de um usuário que não seja root para tarefas desse tipo minimiza o risco de modificação ou exclusão de arquivos importantes ou a realização não intencional de operações perigosas.

      Crie um arquivo chamado ~/kube-cluster/initial.yml na área de trabalho:

      • nano ~/kube-cluster/initial.yml

      A seguir, adicione o seguinte play ao arquivo para criar um usuário não-root com privilégios sudo em todos os servidores. Um play no Ansible é uma coleção de passos a serem realizados que visam servidores e grupos específicos. O seguinte play irá criar um usuário sudo não-root:

      ~/kube-cluster/initial.yml

      
      - hosts: all
        become: yes
        tasks:
          - name: create the 'ubuntu' user
            user: name=ubuntu append=yes state=present createhome=yes shell=/bin/bash
      
          - name: allow 'ubuntu' to have passwordless sudo
            lineinfile:
              dest: /etc/sudoers
              line: 'ubuntu ALL=(ALL) NOPASSWD: ALL'
              validate: 'visudo -cf %s'
      
          - name: set up authorized keys for the ubuntu user
            authorized_key: user=ubuntu key="{{item}}"
            with_file:
              - ~/.ssh/id_rsa.pub
      

      Aqui está um detalhamento do que este playbook faz:

      • Cria um usuário não-root ubuntu.

      • Configura o arquivo sudoers para permitir o usuário ubuntu executar comandos sudo sem uma solicitação de senha.

      • Adiciona a chave pública em sua máquina local (normalmente ~/.ssh/id_rsa.pub) para a lista de chaves autorizadas do usuário remoto ubuntu. Isto o permitirá fazer SSH para dentro de cada servidor como usuário ubuntu.

      Salve e feche o arquivo depois que tiver adicionado o texto.

      Em seguida, rode o playbook localmente executando:

      • ansible-playbook -i hosts ~/kube-cluster/initial.yml

      O comando será concluído dentro de dois a cinco minutos. Na conclusão, você verá uma saída semelhante à seguinte:

      Output

      PLAY [all] **** TASK [Gathering Facts] **** ok: [master] ok: [worker1] ok: [worker2] TASK [create the 'ubuntu' user] **** changed: [master] changed: [worker1] changed: [worker2] TASK [allow 'ubuntu' user to have passwordless sudo] **** changed: [master] changed: [worker1] changed: [worker2] TASK [set up authorized keys for the ubuntu user] **** changed: [worker1] => (item=ssh-rsa AAAAB3...) changed: [worker2] => (item=ssh-rsa AAAAB3...) changed: [master] => (item=ssh-rsa AAAAB3...) PLAY RECAP **** master : ok=5 changed=4 unreachable=0 failed=0 worker1 : ok=5 changed=4 unreachable=0 failed=0 worker2 : ok=5 changed=4 unreachable=0 failed=0

      Agora que a configuração preliminar está completa, você pode passar para a instalação de dependências específicas do Kubernetes.

      Step 3 — Instalando as Dependências do Kubernetes

      Nesta seção, você irá instalar os pacotes no nível do sistema operacional necessários pelo Kubernetes com o gerenciador de pacotes do Ubuntu. Esses pacotes são:

      • Docker – um runtime de container. Este é o componente que executa seus containers. Suporte a outros runtimes como o rkt está em desenvolvimento ativo no Kubernetes.

      • kubeadm – uma ferramenta CLI que irá instalar e configurar os vários componentes de um cluster de uma maneira padrão.

      • kubelet – um serviço/programa de sistema que roda em todos os nodes e lida com operações no nível do node.

      • kubectl – uma ferramenta CLI usada para emitir comandos para o cluster através de seu servidor de API.

      Crie um arquivo chamado ~/kube-cluster/kube-dependencies.yml na área de trabalho:

      • nano ~/kube-cluster/kube-dependencies.yml

      Adicione os seguintes plays ao arquivo para instalar esses pacotes em seus servidores:

      ~/kube-cluster/kube-dependencies.yml

      
      - hosts: all
        become: yes
        tasks:
         - name: install Docker
           apt:
             name: docker.io
             state: present
             update_cache: true
      
         - name: install APT Transport HTTPS
           apt:
             name: apt-transport-https
             state: present
      
         - name: add Kubernetes apt-key
           apt_key:
             url: https://packages.cloud.google.com/apt/doc/apt-key.gpg
             state: present
      
         - name: add Kubernetes' APT repository
           apt_repository:
            repo: deb http://apt.kubernetes.io/ kubernetes-xenial main
            state: present
            filename: 'kubernetes'
      
         - name: install kubelet
           apt:
             name: kubelet
             state: present
             update_cache: true
      
         - name: install kubeadm
           apt:
             name: kubeadm
             state: present
      
      - hosts: master
        become: yes
        tasks:
         - name: install kubectl
           apt:
             name: kubectl
             state: present
      

      O primeiro play no playbook faz o seguinte:

      • Instala o Docker, o runtime de container.

      • Instala o apt-transport-https, permitindo que você adicione fontes HTTPS externas à sua lista de fontes do APT.

      • Adiciona a apt-key do repositório APT do Kubernetes para verificação de chave.

      • Adiciona o repositório APT do Kubernetes à lista de fontes do APT dos seus servidores remotos.

      • Instala kubelet e kubeadm.

      O segundo play consiste de uma única tarefa que instala o kubectl no seu node master.

      Salve e feche o arquivo quando você tiver terminado.

      A seguir, rode o playbook executando localmente:

      • ansible-playbook -i hosts ~/kube-cluster/kube-dependencies.yml

      Na conclusão, você verá uma saída semelhante à seguinte:

      Output

      PLAY [all] **** TASK [Gathering Facts] **** ok: [worker1] ok: [worker2] ok: [master] TASK [install Docker] **** changed: [master] changed: [worker1] changed: [worker2] TASK [install APT Transport HTTPS] ***** ok: [master] ok: [worker1] changed: [worker2] TASK [add Kubernetes apt-key] ***** changed: [master] changed: [worker1] changed: [worker2] TASK [add Kubernetes' APT repository] ***** changed: [master] changed: [worker1] changed: [worker2] TASK [install kubelet] ***** changed: [master] changed: [worker1] changed: [worker2] TASK [install kubeadm] ***** changed: [master] changed: [worker1] changed: [worker2] PLAY [master] ***** TASK [Gathering Facts] ***** ok: [master] TASK [install kubectl] ****** ok: [master] PLAY RECAP **** master : ok=9 changed=5 unreachable=0 failed=0 worker1 : ok=7 changed=5 unreachable=0 failed=0 worker2 : ok=7 changed=5 unreachable=0 failed=0

      Após a execução, o Docker, o kubeadm e o kubelet estarão instalados em todos os seus servidores remotos. O kubectl não é um componente obrigatório e somente é necessário para a execução de comandos de cluster. A instalação dele somente no node master faz sentido nesse contexto, uma vez que você irá executar comandos kubectl somente a partir do master. Contudo, observe que os comandos kubectl podem ser executados a partir de quaisquer nodes worker ou a partir de qualquer máquina onde ele possa ser instalado e configurado para apontar para um cluster.

      Todas as dependências de sistema agora estão instaladas. Vamos configurar o node master e inicializar o cluster.

      Passo 4 — Configurando o Node Master

      Nesta seção, você irá configurar o node master. Antes da criação de quaisquer playbooks, contudo, vale a pena cobrir alguns conceitos como Pods e Plugins de Rede do Pod, uma vez que seu cluster incluirá ambos.

      Um pod é uma unidade atômica que executa um ou mais containers. Esses containers compartilham recursos tais como volumes de arquivo e interfaces de rede em comum. Os pods são a unidade básica de scheduling no Kubernetes: todos os containers em um pod têm a garantia de serem executados no mesmo node no qual foi feito o scheduling do pod.

      Cada pod tem seu próprio endereço IP, e um pod em um node deve ser capaz de acessar um pod em outro node utilizando o IP do pod. Os containers em um único node podem se comunicar facilmente através de uma interface local. Contudo, a comunicação entre pods é mais complicada e requer um componente de rede separado que possa encaminhar o tráfego de maneira transparente de um pod em um node para um pod em outro node.

      Essa funcionalidade é fornecida pelos plugins de rede para pods. Para este cluster vamos utilizar o Flannel, uma opção estável e de bom desempenho.

      Crie um playbook Ansible chamado master.yml em sua máquina local:

      • nano ~/kube-cluster/master.yml

      Adicione o seguinte play ao arquivo para inicializar o cluster e instalar o Flannel:

      ~/kube-cluster/master.yml

      
      - hosts: master
        become: yes
        tasks:
          - name: initialize the cluster
            shell: kubeadm init --pod-network-cidr=10.244.0.0/16 >> cluster_initialized.txt
            args:
              chdir: $HOME
              creates: cluster_initialized.txt
      
          - name: create .kube directory
            become: yes
            become_user: ubuntu
            file:
              path: $HOME/.kube
              state: directory
              mode: 0755
      
          - name: copy admin.conf to user's kube config
            copy:
              src: /etc/kubernetes/admin.conf
              dest: /home/ubuntu/.kube/config
              remote_src: yes
              owner: ubuntu
      
          - name: install Pod network
            become: yes
            become_user: ubuntu
            shell: kubectl apply -f https://raw.githubusercontent.com/coreos/flannel/v0.9.1/Documentation/kube-flannel.yml >> pod_network_setup.txt
            args:
              chdir: $HOME
              creates: pod_network_setup.txt
      

      Aqui está um detalhamento deste play:

      • A primeira tarefa inicializa o cluster executando kubeadm init. A passagem do argumento --pod-network-cidr=10.244.0.0/16 especifica a sub-rede privada que os IPs do pod serão atribuídos. O Flannel utiliza a sub-rede acima por padrão; estamos dizendo ao kubeadm para utilizar a mesma sub-rede.

      • A segunda tarefa cria um diretório .kube em /home/ubuntu. Este diretório irá manter as informações de configuração tais como os arquivos de chaves do admin, que são requeridas para conectar no cluster, e o endereço da API do cluster.

      • A terceira tarefa copia o arquivo /etc/kubernetes/admin.conf que foi gerado a partir do kubeadm init para o diretório home do seu usuário não-root. Isso irá permitir que você utilize o kubectl para acessar o cluster recém-criado.

      • A última tarefa executa kubectl apply para instalar o Flannel. kubectl apply -f descriptor.[yml|json] é a sintaxe para dizer ao kubectl para criar os objetos descritos no arquivo descriptor.[yml|json]. O arquivo kube-flannel.yml contém as descrições dos objetos requeridos para a configuração do Flannel no cluster.

      Salve e feche o arquivo quando você tiver terminado.

      Rode o playbook localmente executando:

      • ansible-playbook -i hosts ~/kube-cluster/master.yml

      Na conclusão, você verá uma saída semelhante à seguinte:

      Output

      PLAY [master] **** TASK [Gathering Facts] **** ok: [master] TASK [initialize the cluster] **** changed: [master] TASK [create .kube directory] **** changed: [master] TASK [copy admin.conf to user's kube config] ***** changed: [master] TASK [install Pod network] ***** changed: [master] PLAY RECAP **** master : ok=5 changed=4 unreachable=0 failed=0

      Para verificar o status do node master, faça SSH nele com o seguinte comando:

      Uma vez dentro do node master, execute:

      Agora você verá a seguinte saída:

      Output

      NAME STATUS ROLES AGE VERSION master Ready master 1d v1.11.1

      A saída informa que o node master concluiu todas as tarefas de inicialização e está em um estado Ready do qual pode começar a aceitar nodes worker e executar tarefas enviadas ao Servidor de API. Agora você pode adicionar os workers a partir de sua máquina local.

      Passo 5 — Configurando os Nodes Worker

      A adição de workers ao cluster envolve a execução de um único comando em cada um. Este comando inclui as informações necessárias sobre o cluster, tais como o endereço IP e a porta do Servidor de API do master, e um token seguro. Somentes os nodes que passam no token seguro estarão aptos a ingressar no cluster.

      Navegue de volta para a sua área de trabalho e crie um playbook chamado workers.yml:

      • nano ~/kube-cluster/workers.yml

      Adicione o seguinte texto ao arquivo para adicionar os workers ao cluster:

      ~/kube-cluster/workers.yml

      
      - hosts: master
        become: yes
        gather_facts: false
        tasks:
          - name: get join command
            shell: kubeadm token create --print-join-command
            register: join_command_raw
      
          - name: set join command
            set_fact:
              join_command: "{{ join_command_raw.stdout_lines[0] }}"
      
      
      - hosts: workers
        become: yes
        tasks:
          - name: join cluster
            shell: "{{ hostvars['master'].join_command }} >> node_joined.txt"
            args:
              chdir: $HOME
              creates: node_joined.txt
      

      Aqui está o que o playbook faz:

      • O primeiro play obtém o comando de junção que precisa ser executado nos nodes workers. Este comando estará no seguinte formato: kubeadm join --token <token> <master-ip>:<master-port> --discovery-token-ca-cert-hash sha256:<hash>. Assim que obtiver o comando real com os valores apropriados de token e hash, a tarefa define isso como um fact para que o próximo play possa acessar essa informação.

      • O segundo play tem uma única tarefa que executa o comando de junção em todos os nodes worker. Na conclusão desta tarefa, os dois nodes worker farão parte do cluster.

      Salve e feche o arquivo quando você tiver terminado.

      Rode o playbook localmente executando:

      • ansible-playbook -i hosts ~/kube-cluster/workers.yml

      Na conclusão, você verá uma saída semelhante à seguinte:

      Output

      PLAY [master] **** TASK [get join command] **** changed: [master] TASK [set join command] ***** ok: [master] PLAY [workers] ***** TASK [Gathering Facts] ***** ok: [worker1] ok: [worker2] TASK [join cluster] ***** changed: [worker1] changed: [worker2] PLAY RECAP ***** master : ok=2 changed=1 unreachable=0 failed=0 worker1 : ok=2 changed=1 unreachable=0 failed=0 worker2 : ok=2 changed=1 unreachable=0 failed=0

      Com a adição dos nodes worker, seu cluster está agora totalmente configurado e funcional, com os workers prontos para executar cargas de trabalho. Antes de fazer o scheduling de aplicações, vamos verificar se o cluster está funcionando conforme o esperado.

      Step 6 — Verificando o Cluster

      Às vezes, um cluster pode falhar durante a configuração porque um node está inativo ou a conectividade de rede entre o master e o worker não está funcionando corretamente. Vamos verificar o cluster e garantir que os nodes estejam operando corretamente.

      Você precisará verificar o estado atual do cluster a partir do node master para garantir que os nodes estejam prontos. Se você se desconectou do node master, pode voltar e fazer SSH com o seguinte comando:

      Em seguida, execute o seguinte comando para obter o status do cluster:

      Você verá uma saída semelhante à seguinte:

      Output

      NAME STATUS ROLES AGE VERSION master Ready master 1d v1.11.1 worker1 Ready <none> 1d v1.11.1 worker2 Ready <none> 1d v1.11.1

      Se todos os seus nodes têm o valor Ready para o STATUS, significa que eles são parte do cluster e estão prontos para executar cargas de trabalho.

      Se, contudo, alguns dos nodes têm NotReady como o STATUS, isso pode significar que os nodes worker ainda não concluíram sua configuração. Aguarde cerca de cinco a dez minutos antes de voltar a executar kubectl get nodes e fazer a inspeção da nova saída. Se alguns nodes ainda têm NotReady como status, talvez seja necessário verificar e executar novamente os comandos nas etapas anteriores.

      Agora que seu cluster foi verificado com sucesso, vamos fazer o scheduling de um exemplo de aplicativo Nginx no cluster.

      Step 7 — Executando Uma Aplicação no Cluster

      Você pode fazer o deploy de qualquer aplicação containerizada no seu cluster. Para manter as coisas familiares, vamos fazer o deploy do Nginx utilizando Deployments e Services para ver como pode ser feito o deploy dessa aplicação no cluster. Você também pode usar os comandos abaixo para outros aplicativos em container, desde que você altere o nome da imagem do Docker e quaisquer flags relevantes (tais como ports e volumes).

      Ainda no node master, execute o seguinte comando para criar um deployment chamado nginx:

      • kubectl run nginx --image=nginx --port 80

      Um deployment é um tipo de objeto do Kubernetes que garante que há sempre um número especificado de pods em execução com base em um modelo definido, mesmo se o pod falhar durante o tempo de vida do cluster. O deployment acima irá criar um pod com um container do registro do Docker Nginx Docker Image.

      A seguir, execute o seguinte comando para criar um serviço chamado nginx que irá expor o app publicamente. Ele fará isso por meio de um NodePort, um esquema que tornará o pod acessível através de uma porta arbitrária aberta em cada node do cluster:

      • kubectl expose deploy nginx --port 80 --target-port 80 --type NodePort

      Services são outro tipo de objeto do Kubernetes que expõe serviços do cluster para os clientes, tanto internos quanto externos. Eles também são capazes de fazer balanceamento de solicitações para vários pods e são um componente integral no Kubernetes, interagindo frequentemente com outros componentes.

      Execute o seguinte comando:

      Isso produzirá uma saída semelhante à seguinte:

      Output

      NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE kubernetes ClusterIP 10.96.0.1 <none> 443/TCP 1d nginx NodePort 10.109.228.209 <none> 80:nginx_port/TCP 40m

      A partir da terceira linha da saída acima, você pode obter a porta em que o Nginx está sendo executado. O Kubernetes atribuirá uma porta aleatória maior que 30000 automaticamente, enquanto garante que a porta já não esteja vinculada a outro serviço.

      Para testar se tudo está funcionando, visite http://worker_1_ip:nginx_port ou http://worker_2_ip:nginx_port através de um navegador na sua máquina local. Você verá a familiar página de boas-vindas do Nginx.

      Se você quiser remover o aplicativo Nginx, primeiro exclua o serviço nginx do node master:

      • kubectl delete service nginx

      Execute o seguinte para garantir que o serviço tenha sido excluído:

      Você verá a seguinte saída:

      [secondary label Output]
      NAME         TYPE        CLUSTER-IP       EXTERNAL-IP           PORT(S)        AGE
      kubernetes   ClusterIP   10.96.0.1        <none>                443/TCP        1d
      

      Para excluir o deployment:

      • kubectl delete deployment nginx

      Execute o seguinte para confirmar que isso funcionou:

      Output

      No resources found.

      Conclusão

      Neste guia, você configurou com sucesso um cluster do Kubernetes no Ubuntu 18.04 usando Kubeadm e Ansible para automação.

      Se você está se perguntando o que fazer com o cluster, agora que ele está configurado, um bom próximo passo seria sentir-se confortável para implantar suas próprias aplicações e serviços no cluster. Aqui está uma lista de links com mais informações que podem orientá-lo no processo:

      • Dockerizing applications - lista exemplos que detalham como containerizar aplicações usando o Docker.

      • Pod Overview - descreve em detalhes como os Pods funcionam e seu relacionamento com outros objetos do Kubernetes. Os pods são onipresentes no Kubernetes, então compreendê-los facilitará seu trabalho.

      • Deployments Overview - fornece uma visão geral dos deployments. É útil entender como os controladores, como os deployments, funcionam, pois eles são usados com frequência em aplicações stateless para escalonamento e na recuperação automatizada de aplicações não íntegras.

      • Services Overview - cobre os serviços ou services, outro objeto frequentemente usado em clusters do Kubernetes. Entender os tipos de serviços e as opções que eles têm é essencial para executar aplicações stateless e stateful.

      Outros conceitos importantes que você pode analisar são Volumes, Ingresses e Secrets, os quais são úteis ao realizar o deploy de aplicações em produção.

      O Kubernetes tem muitas funcionalidades e recursos a oferecer. A Documentação Oficial do Kubernetes é o melhor lugar para aprender sobre conceitos, encontrar guias específicos de tarefas e procurar referências de API para vários objetos.

      Por bsder



      Source link

      WordPress security beyond updates


      One of the reasons for the tremendous popularity of WordPress is that it is open source. As open source software, the bare bones of WordPress are free, and the huge ecosystem of themes, plugins, and other extensions that developers are able to create can be combined in countless different ways to build practically any kind of unique, high-quality website. While this ecosystem is what gives WordPress its flexibility and range of capabilities, it is also the chief source of security concerns for websites using the leading content management platform.

      Of just under 4,000 known WordPress vulnerabilities, plugins make up more than half, according to a recent report by wpscan.org. More than a third are found in the WordPress core, and 11 percent are from Themes. Many of these vulnerabilities can be mitigated simply by applying the next update to your WordPress core and each of your plugins, as developers are alerted of vulnerabilities and make changes to eliminate them.

      Keeping everything up to date and using a complex password are the low-hanging fruit of website security. You can set WordPress to automatically apply core updates, and you can also install a plugin to automatically update your other plugins. There are also security-specific plugins to provide functions like malware scanning and a firewall.

      Beyond these basics, there are a few other simple things that WordPress website operators can do to improve the security of their sites.

      Unreliable or untrustworthy sources

      Plugins from even the most professional and responsible developers have vulnerabilities – it is inevitable that hackers will find new ways to compromise previously secure programs and systems, forcing the developer to react with an update. Most attacks are not new, however, but are directed at vulnerabilities that should have already been dealt with.

      A developer that is slow to close vulnerabilities with updates, or that does so improperly, may leave sites exposed even if everything is up to date. Even worse, a few free or cheap alternatives to popular plugins contain malware or built in-vulnerabilities for the specific purpose of attacking every site they are used in.

      File and folder permissions

      It is generally not necessary or advised for WordPress users to modify permissions for who can read, write, and execute (or run) files and folders. It is important that permissions are set properly, however, and if they have been set too broadly, a malicious actor could potentially take complete control over your site. If you discover a permission has been set to 777, it means that owners, privileged users, and the general public all have permission to modify your site in any way, should they gain access to it.

      To change permissions, you need to use an FTP client. Once you have connected to your site, you can right click on root directories and then edit permissions by clicking on “File permissions” in the menu. Enter the recommended setting in the “Numeric field,” which for most users is 755 for all folder and sub-folders, and make sure that “Recurse into subdirectories” is checked, and click “Apply to directories only.” After you click “OK,” it will take a few seconds to make the changes, after which you can move onto files, by highlighting everything in the sites root folder and following the same procedure to bring up the “File permissions” dialogue box. For most users the permission is set at 644, and “Recurse into subdirectories” and “Apply to files only” are checked.

      Two-factor authentication

      Two-factor authentication, or 2FA, adds an extra layer of security to your WordPress sign-in process. You can apply it with any one of several popular plugins, some of which use the Google Authenticator app to provide the second factor (in the form of a token), often by sending you a one-time password (OTP) to enter along with your usual credentials.

      The plugin may provide options to send the OTP to your email account or mobile device, so that an attacker can only gain access to your site by both knowing your password and stealing your device or hacking your email account. It may also use another factor, such as a QR code that you scan. Some plugins provide an option to use a token along with either a username and password, or just a username. Whichever you choose, select a plugin that has been tested with the current version of WordPress.

      Tools and resources

      There are a number of useful tools and resources that have been created specifically for improving WordPress security, due to the platform’s enormous popularity.

      WPScan.org offers a free tool for scanning WordPress sites for vulnerabilities, allowing you to address them before they are exploited. Companies in the WordPress ecosystem provide useful resources, like the “Learning Center” provided by security plugin developer Wordfence, which includes a nine-part series for dealing with malware. WordPress.org also offers quality documentation and forums, like any major software provider, which contain a lot of answers to security-related questions.

      A quality managed service provider like TMD can also help WordPress users harden their perimeter and protect their websites. Just by taking a step beyond updates, any kind of business can have a secure, cost-effective, beautiful website.



      Source link

      The 70 Best Online Resources to Learn How to Code (Updated 2018)


      If you look back at tech movies of the past, some of them were really ahead of their time. Think back to 1995’s The Net, a film about computer analyst Angela Bennett (played by a young Sandra Bullock) who happens upon a government conspiracy — and dangerous hackers — while debugging a computer program. Not only did the film hit the nail on the head with how prevalent the internet is in our lives, but it also highlighted the power and pervasiveness of programming.

      Call it prophetic, but “hacking” skills — the good kind — are the common currency of the future. With an increasing interest in computer programming and the growth of tech-sector jobs, the time is now to learn a thing or two about 0s and 1s. It’s time to learn to code (no, not morse code).

      Maybe it was tech-of-the-future movies that got you interested in coding as a kid, or perhaps you’re developing a passion for learning mid-career. Whatever the reason, it’s time to go back to school — and with the right resources, you can learn a host of new language skills (no verb conjugating required).

      So what is coding? (If you’ve got some time, start here). Simply put, code is the set of instructions given to computers to perform specific functions. With lines of code, programmers develop the software that powers the devices you encounter every day — from your smartphone to your microwave. Yep, it does a lot.

      Programming is not just a way to build things; coding helps solve problems, aids people in need, and, as Steve Jobs admonished, it teaches you how to think. It’s a skill lauded by presidents, mayors, billionaires, even high fashion supermodels. There’s even a designated Computer Science Education Week. Mark your calendars!

      The good news is you don’t have to live in Silicon Valley or have expensive, high-tech gadgets to learn how to code. Self-taught programming is on the rise, and you can join the masses that are taking to the web to learn the next universal language.

      With the click of a mouse, you can develop a whole new repertoire of programming skills. And we’ve got all the resources to help you learn to code as you start the digital school year.

      Brrrrring! (Code) School is back in session.

      But First, Meet a Self-Taught Programmer

      Before I inundate you with stellar programming resources, allow me to introduce you to a real-life, self-taught coding graduate. Meet Ryan Hanna.

      Ryan Hanna

      Why him? Well, in 2015, more than half of mobile phone users had downloaded a health-related mobile app. And know who created one of the most successful ones? That’s right.

      Hanna began teaching himself to code in January of 2012 using Codeacademy, out of a desire to start creating his own projects.

      “I was tired of just consuming things that other people were building and wanted to try building something of my own,” he says.

      Utilizing lessons from Codeacademy, PhoneGap, and tutorials he found on blogs, he picked up programming skills and began working on his own creation — a new workout app called Sworkit.

      “I transitioned from an IT specialist to a full-time junior developer in the same company I worked for after one year of learning and had started building my own project in my free time,” Hanna says. “This project ended up replacing most of my resume and helped me get my first non-junior developer role where I worked for two years.

      “Along the way, I had met Benjamin Young of Nexercise at a conference, and we ended up deciding to work together on Sworkit full time. His and Greg Coleman’s company Nexercise bought Sworkit and hired me to continue working on it. We’ve since grown to an amazing team of seven and have one of the top workout apps on the market.”

      The growth of Sworkit proved to Hanna — and it should prove to you — that building something amazing is only a few steps away.

      “You can build anything you want,” Hanna says. “Starting with any idea or any design, you can just start building it without any limitations. That feels amazing to go from nothing to something.”

      And learning to code doesn’t have to be overwhelming. Start with baby steps, Hanna says.

      “Learn a broad spectrum of languages and topics at the start, but then pick something small to work on with what you have learned,” he says. “It will help you start something from scratch and get that feeling of adding one little piece at a time. You start to focus on figuring out how to complete each step in sequence and then you have something to show for it at the end as well.”

      A computer science degree isn’t required to get started with a shiny new set of coding skills. Many others have learned, and so can you.

      Here is a hefty list of 70 free or low-cost ways (and more) to get started.

      Self-Guided Tour: Our Complete List of 70 Coding Resources

      1. Games

      We know gaming isn’t time-wasting — rather, it’s an engaging way to learn and practice new concepts as you learn to code. Use these online activities to sharpen your skills.

      CodeFights

      Explore programming in your preferred coding language and on your own time. Whether you’ve got five minutes or five hours, Code Fights allows you to practice for job interviews, play arcade-style coding games, and compete in screen-to-screen challenges

      Cost: Free

      CodeAbbey

      A collection of beginner-to-advanced practice problems that allow you to earn certificates and hone your skills. Consider it a type of fun homework.

      Cost: Free

      Coderbyte

      Choose a coding language and solve challenges; accompanying solutions and tutorials help you cement crucial programming skills with step-by-step instructions

      Cost: Free

      FightCode

      Enter virtual duels by building your own robot using Javascript and challenging other users — programming video games, anyone?

      Cost: Free

      Reddit: Daily Programmer

      Utilize Reddit’s user-based forums to try challenges in a range of different levels and applications — everything from Scrabble-like tests to mazes.

      Cost: Free

      CodinGame

      Play virtual coding games (think: destroying enemy ships with code) that can teach you essential skills and can get you noticed by companies.

      Cost: Free

      CodeEval

      See how you stack up against other coders with a large library of dynamic coding challenges while building a profile and attracting the attention of programmer-seeking companies.

      Cost: Free

      HackerEarth

      Coding activities with purpose. Help solve real-world problems for businesses with innovative programming solutions while joining a community of coders and utilizing practice problems.

      Cost: Free

      HackerRank

      Unearth your inner coding competitor and solve challenges while interacting on a leading recruitment site for companies (meaning, it’s a resume builder!)

      Cost: Free

      Sphere Online Judge

      Become the Obi-Wan of programming by testing out problems and offering your own solutions, while participating in a unique coding community.

      Cost: Free

      Microsoft Imagine

      Enhance your development skills by taking Microsoft’s fun and creative coding projects for a spin.

      Cost: Free

      CodeWars

      A great resource to train yourself, collaborate with others, and create in a variety of programming languages.

      Cost: Free

      Exercism

      Practice problems (consider them mini-quests) for newbies and experts, tailored to your interests, whether you want to learn to code, increase fluency in your chosen language, or develop clean code. Just submit your solutions and get helpful feedback. Works through GitHub.

      Cost: Free

      2. Books

      No dull, dusty textbooks here — these programming tomes can provide you useful reading material.

      The Self-Taught Programmer

      The perfect manual for self-studiers, written by one of coding’s own amateur-turned-professional graduate.

      Cost: $4.99 Kindle Book

      Github Free E-Books

      A countless collection of ebooks on every possible programming topic, like how to learn Python or PHP.

      Cost: Many free — prices vary

      Reddit Free Programming Books

      Another exhaustive collection of online resources to help you increase your coding knowledge.

      Cost: Many free — prices vary

      3. Mentors/Meetups

      Want to meet with like-minded individuals? Find a mentor or coding event in your area.

      Reddit Programming Buddies

      Virtual classified ads for programmers; identify programming comrades that match your unique skills and interests and collaborate on personalized projects.

      Cost: Free

      Perunity

      A matching platform that connects users in a myriad of different fields; outfit a profile with what you offer and what you want to learn and begin sharing knowledge with other groups.

      Cost: Free

      Pair With Me

      Utilize the site’s Pair With Me button to encourage collaboration from your own website or contact form. Also, check out the provided collection of resources and guides for programmer pairing.

      Cost: Free

      CodeNewbies Twitter

      This social media handle hosts a live, weekly chat every Wednesday where users can ask questions and converse with other programmers — beginners and experts alike.

      Cost: Free

      Meetup

      A general connection platform that allows you to tailor specific meetup requests in your area. A good place to start? Tech Meetups.

      Cost: Prices vary

      Hackathons

      Not unlike a hip, adult slumber party; these all-night coding parties allow you to gather with like-minded learners and develop new skills as you tackle team programming projects.

      Cost: Prices vary

      Local Computer Science Classes

      For those looking to feel like a student again. Another Code.org resource that allows you to find computer science courses local to your area.

      Cost: Prices vary

      Girl Develop It

      A female-focused nonprofit that provides resources for computer science-interested women. Find your local chapter and attend programming events.

      Cost: Prices vary

      Did You Know? DreamHost has partnered with Girl Develop It to sponsor WordPress courses nationwide.

      Coder Match

      Link your GitHub account to find coding buddies that share similar programming goals and projects.

      Cost: Free

      Code Buddies

      A large community of programmers who connect via Slack and organized study (screen-sharing) hangouts. Make your hangouts as unique as your project.

      Cost: Free

      4. Videos

      Hunker down: it’s movie night. Time to break out the popcorn and watch as YouTubers — and others — share their knowledge. (Bonus: No Redbox fees).

      DevTips

      A Google employee shares weekly video lessons that address topics of web design and development.

      CSS-Tricks

      The YouTube channel of a matching site that addresses much more than just CSS.

      Derek Banas

      Your wish is Derek Banas command; the YouTuber makes video tutorials based on the requests and questions from viewers, so ask away! His tailored videos also include multi-weekly live streams. Along with an extensive collection of programming tutorials, he’s also got in-depth guides on how to create video games. Score!

      Coder’s Guide

      Helpful step-by-step web development tutorials covering everything from responsive web design to splash screens.

      The New Boston

      Covering all things computers, The New Boston offers detailed videos for every step of your programming journey — even for beginners.

      Programming Knowledge

      A great starting point for beginners; these easy-to-digest video help learners manage the ins-and-outs of different programming languages.

      Ted Talks

      A playlist of seven top-tier talks from Ted Talks’ best speakers, covering topics like teaching kids to code and improving government through programming.

      Command Line Power User

      A handy video series for web developers learning how to interact with computer programs.

      My Code School

      This educational channel has more than 330,000 subscribers for a reason: the folks behind it know their stuff. With tons of videos on a host of programming languages and live content, you can get a crash course on any programming subject you want to learn about.

      Looking for additional coding movie makers? Here are a few more you can check out.

      5. eCourses

      Choose from a handful of virtual courses or coding boot camps to learn new skills — at free or budget-friendly costs.

      GitHub

      A coder-must platform that helps programmers collaborate with each other as they save code online, view changes, and discuss issues.

      Cost: Paid (from $7 per month) and free plans available

      Bitbucket

      Another resource that makes coding a team effort; works in conjunction with Git to help programmers work jointly on projects.

      Cost: Paid (from $10 per month) and free plans available

      Open Culture

      A full list of all kinds of online computer courses from distinguished universities — available in various formats for easy accessibility.

      Cost: Free

      Code Avengers

      Whether you want to learn how to build websites, apps, or games, this resource has helpful lessons, quizzes, and project-based learning tools for creating and real-life problem solving, tailored to your own individual programming path. They even provide an educational environment for junior coders.

      Cost: $29 per month; $150 for six months

      Code.org

      Moana, Star Wars, and Minecraft — all subjects incorporated into one-hour tutorials provided by nonprofit Code.org. These easy-to-digest courses are accessible for learners of all levels and ages, and provide useful hands-on experience for future programming gurus

      Cost: Free

      Reddit

      Not just a programmer’s favorite; this Reddit page has a collective list of interactive coding tutorials gathered from around the web on various topics, from mobile iOs or Android development to info on different programming languages. (Plus, you can even watch people code!)

      Cost: Free

      GitHub Curated Programming Resources

      Another exhaustive list of coding resources, plus, a helpful introduction that guides beginners on where to start.

      Cost: Free

      Codeacademy

      Ryan Hanna’s alma mater is helping educate the world in programming; choose from a catalog of courses that meet your learning needs and get coding.

      Cost: Free

      David Walsh

      Web developer Walsh shares a host of programming tutorials in addition to sharing demos and info about coding conferences.

      Cost: Free

      Open Culture

      A collection of computer science courses and resources available right from your screen and in multiple formats.

      Cost: Free

      Treehouse

      A course-focused site that offers resources for learning, practicing, and earning badges that boost your skills. Students can earn anything from app-building to website-creation.

      Cost: Free 7-day trial, $25 (Basic Plan) or $49 (Pro Plan) a month after

      Coursera

      Take courses straight from actual universities in a variety of specializations. This site partners with top schools to offer education in programming, data science, business, and more.

      Cost: Prices vary

      EdX

      Students choose from an extensive collection of self-paced computer science courses fueled by university curriculum — it was founded by Harvard and MIT in 2012.

      Cost: Free, professional certificates at a cost

      Free Code Camp

      Complete challenges and building projects that can help you build skills, even acquire developer jobs. Plus, Free Code Camp tasks have practical applications, like aiding nonprofits with open source projects.

      Cost: Per its name, free

      General Assembly Dash

      Learn coding basics from your browser — the step-by-step guided fundamentals can aid you in building your next super-site.

      Cost: Free

      Udacity

      Earn a nanodegree — an online certification with provided course materials and instructor guidance — in one of seventeen available tech tracks. Learn in-demand job skills at your own pace.

      Cost: Prices vary (but plan for a cost of at least a few hundred every month).

      Solo Learn

      Learn to code on the go with online courses or a travel-friendly app. Topics feature tons of courses and quizzes, plus social learning components; there’s even a “Code Playground” for experimental development.

      Cost: Free

      Udemy

      Choose from more than 45,000 courses tailored to your own personal programming syllabus rated and reviewed by peers.

      Cost: Prices vary

      Lynda

      A learning platform filled with engaging courses taught by industry gurus.

      Cost: Free 30-day trial, prices vary after

      Self Taught Coders

      Email courses designed to help you launch a career in web development and propel your ideas into real-life web applications.

      Cost: Prices vary, some free

      MarkSheet

      An HTML and CSS tutorial that starts at the web’s bare bones and gets gradually more detailed as the course progresses — an easy-to-understand intro for beginners.

      Cost: Free

      Reddit: Learn Programming

      A smart guide with an abundance of helpful resources for every step of your self-taught programming journey.

      Cost: Free

      Haven’t found your perfect fit? Try this: a few more places to code for free.

      6. Podcasts

      Load up your device with audio coding lessons and listen on your commute or during your workout.

      Coding Blocks

      Shop talk about development best practices relevant to a number of different programming languages.

      Cost: Free

      Dev Radio

      A by developers, for developers podcast that shares up-and-coming programming news. Cost: Free

      Software Engineering Daily

      Featured interviews with experts that touch on tech topics like mobile app development and developer testing.

      Cost: Free

      Developer Tea

      A snackable-size podcast designed for busy schedules. Listen to quick bites on all kinds of developer-designed details.

      Cost: Free

      Programming Throwdown

      A perfect podcast if you want a little taste of everything; each show covers a different programming language so you can expand your coding knowledge with each episode.

      Cost: Free

      Coding Newbie

      This weekly podcast features stories and useful lessons from other individuals who are on their self-taught programming path.

      Cost: Free

      Learn to Code With Me

      Laurence Bradford’s weekly podcast helps self-taught coders transition to the tech field with useful real-world examples and tips on developing marketable skills and enhancing your resume.

      Cost: Free

      Need more earworms? Try additional podcasts here, including language- and task-specific channels.

      7. For Children

      Turns out, it’s never too soon to start introducing your tots to their first bytes.

      Computer Science for Babies

      A book series designed to help your little ones make connections to computer science principles during early development.

      Cost: Prices vary

      HTML for Babies

      A three-volume collection of board books that introduce your infants to computer science fundamentals. In conjunction with site Code Babies.

      Cost: Amazon, $1.73 each

      Treehouse: When Should Kids Learn to Code?

      Tips for helping kids to get a start in programming.

      Cost: Free

      Code.org Student

      A youthful resource for finding online courses or local classes. Includes games and activities.

      Cost: Free

      MoonHack

      A record-setting event for Code Club where kids ages 7-18 around the world join together to tackle projects — MoonHack’s or your own (moon-themed, of course). 2017’s MoonHack event brought together more than 28,000 youth.

      Cost: Free

      Code Your Own Games!

      Entice youth early to get involved in coding with this easy-to-follow (and super fun) visual guide that helps them learn to program their own games. Gaming + learning = win-win.

      Cost: Amazon, $16.16

      Got Questions?

      Our collection of resources provides a comprehensive list of places to initiate your self-taught programming journey, from beginning fundamentals to jump-starting your coding career. But along the way, you might hit a few roadblocks. Well, we’re here for you.

      Maybe you don’t know what programming language to start learning. Easy. Try an interactive quiz or infographic that guides your journey based on your individual goals and interests (like, creating a game, or developing an iOS or Android app).

      Struggling with framework questions, or need to fix a bug or in your code? Try utilizing Stack Overflow, a coder’s knowledge-sharing community. Want to automate tedious tasks while using Microsoft devices? Do it with Windows PowerShell. Trying to learn how to master an object-oriented programming language? Visualize with the Understand tool.

      Or perhaps you’re looking for useful apps or a development environment to practice in? We’ve got you covered. Try some note-taking apps that help while you code and useful coding playgrounds like Code Pen, JSFiddle, or Limnor Studio (visual programming) to get your feet wet.

      Any more questions? Let us know.

      Take Notes

      Ready for your homework? Time to get coding.

      Pick a course, a video, a podcast, or a coding game. Start there and start small. With our complete guide to coding resources, you have everything you need to start building your own projects and becoming fluent in your new language.

      Fill Us In

      Are you a self-taught programmer? How did you learn to code? What advice would you give to other wannabe coders? Share your story — and your advice — with us in the DreamHost Community!





      Source link