One place for hosting & domains

      Should I Switch Web Hosts? How to Know When It’s Time to Migrate Your Site

      When it comes to starting a website, web hosting is one of the most crucial yet most confusing aspects to tackle. With dozens of providers on the market, it can be hard to cut through the noise and figure out which one offers the best plan for you.

      Fortunately, several signs will make it clear when it’s time to move to a new host. While they’re not so pleasant to deal with in the moment, these issues may lead you to a better service provider that can help you boost your site’s success.

      In this post, we’ll discuss these signs and how to spot them on your website. Then we’ll explain how to migrate your site to a new web hosting platform. Let’s get started!

      Have a website? We’ll move it for you!

      Migrating to a new web hosting provider can be a pain. We’ll move your existing site within 48 hours without any interruption in service. Included FREE with any DreamPress plan.

      How to Know When It’s Time to Migrate (6 Tell-Tale Signs)

      It’s possible you’ve been experiencing problems with your website for a while now without really knowing why. In some cases, it may be that your web hosting provider isn’t a good fit for your website. These six signs will let you know it’s time to switch web hosts.

      1. You’re Experiencing More Downtime Than Usual

      Any time your website is unavailable to users, it’s considered ‘down.’ Even if your site is only unavailable for seconds at a time, it could cause serious problems. For starters, downtime makes your website appear unreliable and low-quality to both users and search engines.

      If your site is experiencing frequent outages, your users will come to find they can’t rely on it to be available when needed. The Google algorithm will account for this, and your search engine rankings will fall as well, hurting your site’s visibility.

      Plus, if your site generates revenue, you’ll be missing out on income every time your site has an outage. If your site is down often or for long periods of time, you could be losing hundreds or even thousands of dollars. When you’re running an online store, uptime truly affects your bottom line.

      Web hosting is one of the most common causes of website downtime, as there are many ways in which your server can impact your site’s availability, including:

      • The quality and reliability of your hosting equipment
      • The type of server your website is on, as shared servers tend to become overloaded more quickly than other types of servers.
      • Your host’s security features, since malicious attacks can lead to downtime.

      So, if you keep finding your website is down, there’s a fair chance your host may have something to do with it. Moving to a more reliable server is the best thing for your site in a situation like this.

      2. Your Website’s Loading Speed Is Slow

      Site speed is also key to Search Engine Optimization (SEO), users’ opinions of your site, and your conversion rate. It’s wise to test your site’s speed every once in a while using tools such as Google PageSpeed Insights and Pingdom to make sure your loading times are staying low and to fix any performance issues.

      Pingdom’s results screen.

      While a crowded server can certainly slow your loading times, your server’s location also plays a role in how fast your site delivers information to visitors. Servers located far away from end users aren’t able to serve them content as quickly.

      An easy way to determine if this is the case for your website is to use Pingdom to test your site speed from a variety of locations. If your site loads quickly from some places yet takes a long time to load in others, you’ll know server location is causing speed issues for users in those regions.

      If your host only has servers in one location and doesn’t offer a Content Delivery Network (CDN), it’s almost guaranteed that some portion of your users will experience less-than-ideal site speed. It may be worth looking into hosts with more or different locations, or ones offering a CDN.

      3. Customer Service Isn’t Helpful

      A solid relationship with your web host is priceless. For starters, there are going to be times when server-related errors occur on your site. In these instances, you’ll need to be able to get ahold of your host quickly to resolve the issue and get your site back up. Plus, you may sometimes have questions about billing or other account details.

      However, the best hosts also offer support in other areas of website management. For example, many hosts provide troubleshooting guidance for different types of errors on your website or support for platforms such as WordPress.

      If your host is difficult to get in touch with, provides inadequate solutions, or doesn’t offer support in areas directly related to your hosting account, consider switching to a new provider. While you may be able to get by without quality customer support, at some point, you’ll have to reach someone for help with a server-related problem, so you’ll want a reliable team at your back.

      4. You Need More Space Than Your Current Provider Can Offer

      Most websites start small and grow over time. Your current host may have been a great fit when you were first launching your site, but if your traffic levels have increased significantly, this may no longer be the case.

      As your site accumulates more recurring users, you’ll need a server that can handle more traffic as well as more and larger website files. Moving from shared hosting to a dedicated server can help, but switching hosts can often provide a greater benefit.

      Some providers specialize in shared or Virtual Private Network (VPN) hosting and may not offer dedicated servers. As such, if your site continues to grow, you’ll need a dedicated web hosting service at some point — so a switch may be inevitable.

      Other hosts may have dedicated servers available, but still not offer as much storage as you need. Ultimately, you’ll want to compare plans between companies to see which one offers the most space for the best price.

      5. It’s Getting Too Expensive to Stay With Your Current Host

      Web hosting is a recurring expense. It’s also sometimes the largest expense associated with running a website, especially for WordPress users working with a free Content Management System (CMS) and mainly free plugins and themes.

      It’s true that you often get what you pay for with hosting. However, there are also times when an expensive plan isn’t necessary. If your site is still small and not using the amount of server space you’re paying for, or if your current hosting plan comes with several features you never touch, you’re probably paying too much.

      There’s no sense in breaking the bank to host your website when there are plenty of affordable options available. For example, we offer high-quality managed WordPress hosting plans for as low as $16.95 per month.

      If you’re shelling out more money for web hosting than what your website brings in, you might want to consider downsizing or switching hosts to stay within your budget. Plus, it never hurts to pocket a little extra cash each month.

      6. Server Security Is Sub-Par

      As we mentioned earlier in this post, hosts are responsible for securing their servers. Not every provider is as diligent as they should be when it comes to security, and hackers will sometimes exploit weaknesses in your server to gain access to your site.

      This can be detrimental to your website for multiple reasons, including:

      • The loss of parts or all of your site due to a malicious attack that destroys key files and data.
      • Compromised user data, including sensitive information such as private records and credit card details.
      • Decreased credibility, as users will see your site as less reliable if it’s hacked.

      Investing in secure hosting is a smart move. Even if you have to pay a little extra or go through the trouble of migrating to a new host, you’ll save yourself a lot of trouble down the line.

      Some security features you may want to keep an eye out for are Secure Sockets Layer (SSL) certificates, malware scanning, and server firewalls. Of course, no matter how secure your server is, you should always follow security best practices for your site itself, too.

      How to Migrate Your Website to a New Hosting Provider

      If you’ve considered the signs mentioned above and determined you should switch hosting providers, you’ll need to migrate your website. This requires you to copy all your website’s files and move them to your new hosting account.

      Typically, the migration process is pretty involved. You’ll have to contact your current host, back up your site files, then use Secure File Transfer Protocol (SFTP) and a client such as FileZilla to connect to your new server and upload your files. You’ll also want to consider transferring your domain since there are benefits to keeping your domain registration and web hosting under one roof.

      As you might imagine, there are a lot of things that could go wrong during this process. For example, corrupted backups are always a possibility, and using SFTP still poses a risk to your site’s files as you could mistakenly delete some or all of them (we recommend users always have a recent backup of their site on hand).

      These things considered, it’s helpful if you can get an expert on board to migrate your site for you. Fortunately, if you’re a WordPress user and have decided to switch to DreamHost, our managed WordPress hosting plans include free website migration services.

      DreamHost’s WordPress migration services.

      We’ll handle moving your site at no extra cost. If you’d prefer one of our shared hosting plans or have a website built without using WordPress, never fear. You can still take advantage of our migration service for just $99.

      Our migration experts will get your site moved to your new hosting account within 48 hours of your request. You’ll also avoid downtime altogether, so you don’t have to worry about negatively impacting your users’ experience while you move your site and get acquainted with the DreamHost control panel.

      Looking for a New Hosting Provider?

      We make moving easy. Our hassle-free, high-performance WordPress hosting includes a FREE professional migration service ($99 savings)!

      Switching Web Hosts

      Hosting can be one of the most confusing aspects of owning a website. With so many options to choose from, it can be difficult to know if your web hosting provider is the best one available for your needs.

      If you’ve noticed these issues on your website and have decided it’s time for a change, consider checking out our DreamPress hosting plans. Our managed WordPress hosting service will provide you with the speed, support, and security your WordPress site needs. Plus, you’ll be able to use our site migration services for free.

      Source link

      Como Provisionar e Gerenciar Hosts Remotos do Docker com Docker Machine no Ubuntu 18.04


      Docker Machine é uma ferramenta que facilita o provisionamento e o gerenciamento de vários hosts Docker remotamente a partir do seu computador pessoal. Esses servidores são comumente chamados de hosts Dockerizados e são usados para executar containers do Docker.

      Embora o Docker Machine possa ser instalado em um sistema local ou remoto, a abordagem mais comum é instalá-lo em seu computador local (instalação nativa ou máquina virtual) e usá-lo para provisionar servidores remotos Dockerizados.

      Embora o Docker Machine possa ser instalado na maioria das distribuições Linux, bem como no MacOS e no Windows, neste tutorial, você o instalará em sua máquina local executando Ubuntu 18.04 e o usará para provisionar Droplets Dockerizados na DigitalOcean. Se você não tem uma máquina local Ubuntu 18.04, você pode seguir estas instruções em qualquer servidor Ubuntu 18.04.


      Para seguir este tutorial, você vai precisar do seguinte:

      • Uma máquina local ou servidor executando o Ubuntu 18.04 com o Docker instalado. Veja Como Instalar e Usar o Docker no Ubuntu 18.04 para instruções.

      • Um token de API da DigitalOcean. Se você não tiver um, gere-o usando este guia. Quando você gerar um token, certifique-se de que ele tenha um escopo de leitura e gravação. Esse é o padrão, portanto, se você não alterar nenhuma opção enquanto estiver gerando, ela terá recursos de leitura e gravação.

      Passo 1 — Instalando o Docker Machine

      Para usar a Docker Machine, você deve primeiro instalá-lo localmente. No Ubuntu, isso significa baixar um punhado de scripts do repositório oficial do Docker no GitHub.

      Para baixar e instalar o binário do Docker Machine, digite:

      • wget$(uname -s)-$(uname -m)

      O nome do arquivo deve ser docker-machine-Linux-x86_64. Renomeie-o para docker-machine para torná-lo mais fácil de trabalhar:

      • mv docker-machine-Linux-x86_64 docker-machine

      Torne-o executável:

      Mova ou copie-o para o diretório /usr/local/bin para que ele esteja disponível como um comando do sistema:

      • sudo mv docker-machine /usr/local/bin

      Verifique a versão, o que indicará que ele está corretamente instalado:

      Você verá uma saída semelhante a esta, exibindo o número da versão e a compilação:


      docker-machine version 0.15.0, build b48dc28d

      O Docker Machine está instalado. Vamos instalar algumas ferramentas auxiliares adicionais para facilitar o trabalho com o Docker Machine.

      Passo 2 — Instalando Scripts Adicionais do Docker Machine

      Existem três scripts Bash no repositório GitHub do Docker Machine que você pode instalar para facilitar o trabalho com os comandos docker e docker-machine. Quando instalados, esses scripts fornecem o recurso de auto-completar comandos e de personalização do prompt.

      Nesta etapa, você irá instalar esses três scripts no diretório /etc/bash_completion.d em sua máquina local, baixando-os diretamente do repositório GitHub do Docker Machine.

      Nota: Antes de baixar e instalar um script da internet em um local disponível do sistema, você deve inspecionar o conteúdo do script primeiro, visualizando a URL de origem em seu navegador.

      O primeiro script permite que você veja a máquina ativa no seu prompt. Isso é útil quando você está trabalhando e alternando entre várias máquinas Dockerizadas. O script é chamado de docker-machine-prompt.bash. Baixe-o

      • sudo wget -O /etc/bash_completion.d/docker-machine-prompt.bash

      Para completar a instalação deste arquivo, você terá que modificar o valor da variável PS1 no seu arquivo .bashrc. A variável PS1 é uma variável de shell especial usada para modificar o prompt de comando do Bash. Abra o ~/.bashrc em seu editor:

      Dentro desse arquivo, existem três linhas que começam com PS1. Elas devem se parecer com estas:


      PS1='${debian_chroot:+($debian_chroot)}[33[01;32m]u@h[33[00m]:[33[01;34m]w[33[00m]$ '
      PS1='${debian_chroot:+($debian_chroot)}u@h:w$ '
      PS1="[e]0;${debian_chroot:+($debian_chroot)}u@h: wa]$PS1"

      Para cada linha, insira $(__docker_machine_ps1 " [%s]") perto do final, conforme mostrado no exemplo a seguir:


      PS1='${debian_chroot:+($debian_chroot)}[33[01;32m]u@h[33[00m]:[33[01;34m]w[33[00m]$(__docker_machine_ps1 " [%s]")$ ' ... PS1='${debian_chroot:+($debian_chroot)}u@h:w$(__docker_machine_ps1 " [%s]")$ ' ... PS1="[e]0;${debian_chroot:+($debian_chroot)}u@h: wa]$(__docker_machine_ps1 " [%s]")$PS1"

      Salve e feche o arquivo.

      O segundo script é chamado de docker-machine-wrapper.bash. Ele adiciona um subcomando use ao comando docker-machine, facilitando significativamente a alternância entre os hosts Docker. Para baixá-lo, digite:

      • sudo wget -O /etc/bash_completion.d/docker-machine-wrapper.bash

      O terceiro script é chamado de docker-machine.bash. Ele adiciona o auto-completar ao bash para os comandos docker-machine. Baixe-o usando:

      • sudo wget -O /etc/bash_completion.d/docker-machine.bash

      Para aplicar as alterações feitas até agora, feche e reabra seu terminal. Se você estiver logado na máquina via SSH, saia da sessão e faça o login novamente, e você terá o auto-completar de comandos para os comandos docker e docker-machine.

      Vamos testar as coisas criando um novo host Docker com o Docker Machine.

      Passo 3 — Provisionando um Host Dockerizado Usando o Docker Machine

      Agora que você tem o Docker e o Docker Machine em execução em sua máquina local, é possível provisionar um Droplet Dockerizado em sua conta da DigitalOcean usando o comando docker-machine create do Docker Machine. Se você ainda não o fez, atribua seu token da API da DigitalOcean a uma variável de ambiente:

      • export DOTOKEN=seu-token-de-api

      NOTA: Este tutorial usa DOTOKEN como a variável bash para o token da API da DigitalOcean. O nome da variável não precisa ser DOTOKEN e não precisa estar em maiúsculas.

      Para tornar a variável permanente, coloque-a em seu arquivo ~/.bashrc. Este passo é opcional, mas é necessário se você quiser que o valor persista entre sessões de shell.

      Abra esse arquivo com o nano:

      Adicione esta linha ao arquivo:


      export DOTOKEN=seu-token-de-api

      Para ativar a variável na sessão de terminal atual, digite:

      Para chamar o comando docker-machine create com sucesso, você deve especificar o driver que deseja usar, bem como o nome da máquina. O driver é o adaptador para a infraestrutura que você vai criar. Existem drivers para provedores de infraestrutura de nuvem, bem como drivers para várias plataformas de virtualização.

      Vamos usar o driver digitalocean. Dependendo do driver selecionado, você precisará fornecer opções adicionais para criar uma máquina. O driver digitalocean requer o token da API (ou a variável que o fornece) como seu argumento, junto com o nome da máquina que você deseja criar.

      Para criar sua primeira máquina, digite este comando para criar um Droplet na DigitalOcean chamado docker-01:

      • docker-machine create --driver digitalocean --digitalocean-access-token $DOTOKEN docker-01

      Você verá esta saída enquanto o Docker Machine cria o Droplet:


      ... Installing Docker... Copying certs to the local machine directory... Copying certs to the remote machine... Setting Docker configuration on the remote daemon... Checking connection to Docker... Docker is up and running! To see how to connect your Docker Client to the Docker Engine running on this virtual machine, run: docker-machine env ubuntu1804-docker

      O Docker Machine cria um par de chaves SSH para o novo host para que ele possa acessar o servidor remotamente. O Droplet é provisionado com um sistema operacional e o Docker é instalado. Quando o comando estiver concluído, o seu Droplet Docker estará em funcionamento.

      Para ver a máquina recém-criada a partir da linha de comando, digite:

      A saída será semelhante a esta, indicando que o novo host Docker está em execução:


      NAME ACTIVE DRIVER STATE URL SWARM DOCKER ERRORS docker-01 - digitalocean Running tcp:// v18.06.1-ce

      Agora vamos ver como especificar o sistema operacional quando criamos uma máquina.

      Passo 4 — Especificando o SO Básico e as Opções de Droplet ao Criar um Host Dockerizado

      Por padrão, o sistema operacional básico usado ao criar um host Dockerizado com o Docker Machine é supostamente o Ubuntu LTS mais recente. No entanto, no momento desta publicação, o comando docker-machine create ainda está usando o Ubuntu 16.04 LTS como o sistema operacional base, embora o Ubuntu 18.04 seja a edição mais recente do LTS. Portanto, se você precisar rodar o Ubuntu 18.04 em uma máquina recém-provisionada, você terá que especificar o Ubuntu junto com a versão desejada passando a flag --digitalocean-image para o comandodocker-machine create.

      Por exemplo, para criar uma máquina usando o Ubuntu 18.04, digite:

      • docker-machine create --driver digitalocean --digitalocean-image ubuntu-18-04-x64 --digitalocean-access-token $DOTOKEN docker-ubuntu-1804

      Você não está limitado a uma versão do Ubuntu. Você pode criar uma máquina usando qualquer sistema operacional suportado na DigitalOcean. Por exemplo, para criar uma máquina usando o Debian 8, digite:

      • docker-machine create --driver digitalocean --digitalocean-image debian-8-x64 --digitalocean-access-token $DOTOKEN docker-debian

      Para provisionar um host Dockerizado usando o CentOS 7 como o SO base, especifique centos-7-0-x86 como o nome da imagem, da seguinte forma:

      • docker-machine create --driver digitalocean --digitalocean-image centos-7-0-x64 --digitalocean-access-token $DOTOKEN docker-centos7

      O sistema operacional básico não é a única opção que você tem. Você também pode especificar o tamanho do Droplet. Por padrão, é o menor Droplet, que tem 1 GB de RAM, uma única CPU e um SSD de 25 GB.

      Encontre o tamanho do Droplet que você deseja usar procurando o slug correspondente na documentação da API da DigitalOcean.

      Por exemplo, para provisionar uma máquina com 2 GB de RAM, duas CPUs e um SSD de 60 GB, use o slug s-2vcpu-2gb:

      docker-machine create --driver digitalocean --digitalocean-size s-2vcpu-2gb --digitalocean-access-token $DOTOKEN docker-03

      Para ver todas as flags específicas para criar um Docker Machine usando o driver da DigitalOcean, digite:

      • docker-machine create --driver digitalocean -h

      Dica: Se você atualizar a página de Droplet do seu painel da DigitalOcean, verá as novas máquinas que você criou usando o comando docker-machine.

      Agora vamos explorar alguns dos outros comandos do Docker Machine.

      Passo 5 — Executando Comandos Adicionais do Docker Machine

      Você viu como provisionar um host Dockerizado usando o subcomando create e como listar os hosts disponíveis para o Docker Machine usando o subcomando ls. Nesta etapa, você aprenderá alguns subcomandos mais úteis.

      Para obter informações detalhadas sobre um host Dockerizado, use o subcomando inspect, da seguinte forma:

      • docker-machine inspect docker-01

      A saída inclui linhas como as da saída mostrada abaixo. A linha Image revela a versão da distribuição Linux usada, e a linha Size indica o slug do tamanho:


      ... { "ConfigVersion": 3, "Driver": { "IPAddress": "", "MachineName": "docker-01", "SSHUser": "root", "SSHPort": 22, ... "Image": "ubuntu-16-04-x64", "Size": "s-1vcpu-1gb", ... }, ---

      Para imprimir a configuração de conexão de um host, digite:

      • docker-machine config docker-01

      A saída será smelhante a esta:


      --tlsverify --tlscacert="/home/kamit/.docker/machine/certs/ca.pem" --tlscert="/home/kamit/.docker/machine/certs/cert.pem" --tlskey="/home/kamit/.docker/machine/certs/key.pem" -H=tcp://

      A última linha na saída do comando docker-machine config revela o endereço IP do host, mas você também pode obter essa informação digitando:

      • docker-machine ip docker-01

      Se você precisar desligar um host remoto, você pode usar docker-machine para pará-lo:

      • docker-machine stop docker-01

      Verifique se está parado:

      A saída mostra que o status da máquina mudou:


      NAME ACTIVE DRIVER STATE URL SWARM DOCKER ERRORS docker-01 - digitalocean Stopped Unknown

      Para iniciá-la novamente, use o subcomando start:

      • docker-machine start docker-01

      Em seguida, revise seu status novamente:

      Você verá que o STATE agora está definido como Running para o host:


      NAME ACTIVE DRIVER STATE URL SWARM DOCKER ERRORS docker-01 - digitalocean Running tcp:// v18.06.1-ce

      Em seguida, vamos ver como interagir com o host remoto usando o SSH.

      Passo 6 — Executando Comandos em um Host Dockerizado via SSH

      Neste ponto, você está recebendo informações sobre suas máquinas, mas você pode fazer mais do que isso. Por exemplo, você pode executar comandos nativos do Linux em um host Docker usando o subcomando ssh do docker-machine a partir do seu sistema local. Esta seção explica como executar comandos ssh via docker-machine, bem como abrir uma sessão SSH para um host Dockerizado.

      Supondo que você provisionou uma máquina com o Ubuntu como sistema operacional, execute o seguinte comando em seu sistema local para atualizar o banco de dados de pacotes no host Docker:

      • docker-machine ssh docker-01 apt-get update

      Você pode até mesmo aplicar atualizações disponíveis usando:

      • docker-machine ssh docker-01 apt-get upgrade

      Não tem certeza de qual kernel seu host Docker remoto está usando? Digite o seguinte:

      • docker-machine ssh docker-01 uname -r

      Finalmente, você pode efetuar login no host remoto com o comando docker machine ssh:

      • docker-machine ssh docker-01

      Você estará logado como usuário root e verá algo semelhante ao seguinte:

      Welcome to Ubuntu 16.04.5 LTS (GNU/Linux 4.4.0-131-generic x86_64)
       * Documentation:
       * Management:
       * Support:
        Get cloud support with Ubuntu Advantage Cloud Guest:

      14 packages can be updated.
      10 updates are security updates.

      Faça o logout digitando exit para retornar à sua máquina local.

      Em seguida, direcionaremos comandos do Docker em nosso host remoto.

      Passo 7 — Ativando um Host Dockerizado

      A ativação de um host Docker conecta seu cliente Docker local a esse sistema, o que possibilita a execução de comandos docker comuns no sistema remoto.

      Primeiro, use o Docker Machine para criar um novo host do Docker chamado docker-ubuntu usando o Ubuntu 18.04:

      • docker-machine create --driver digitalocean --digitalocean-image ubuntu-18-04-x64 --digitalocean-access-token $DOTOKEN docker-ubuntu

      Para ativar um host Docker, digite o seguinte comando:

      • eval $(docker-machine env machine-name)

      Alternativamente, você pode ativá-lo usando este comando:

      • docker-machine use machine-name

      Uma dica ao trabalhar com vários hosts Docker, é que o comando docker-machine use é o método mais fácil de alternar de um para o outro.

      Depois de digitar qualquer um desses comandos, seu prompt será alterado para indicar que o cliente Docker está apontando para o host do Docker remoto. Ele terá essa forma. O nome do host estará no final do prompt:

      username@localmachine:~ [docker-01]$

      Agora, qualquer comando docker que você digitar neste prompt de comando será executado naquele host remoto.

      Execute docker-machine ls novamente:

      Você verá um asterisco sob a coluna ACTIVE para docker-01:


      NAME ACTIVE DRIVER STATE URL SWARM DOCKER ERRORS docker-01 * digitalocean Running tcp:// v18.06.1-ce

      Para sair do host Docker remoto, digite o seguinte:

      Seu prompt não mostrará mais o host ativo.

      Agora vamos criar containers na máquina remota.

      Passo 8 — Criando Containers Docker em um Host Dockerizado Remoto

      Até agora, você provisionou um Droplet Dockerizado na sua conta DigitalOcean e o ativou — ou seja, seu cliente Docker está apontando para ele. O próximo passo lógico é criar containers nele. Por exemplo, vamos tentar executar o container Nginx oficial.

      Utilize docker-machine use para selecionar sua máquina remota:

      • docker-machine use docker-01

      Em seguida, execute este comando para executar um container Nginx nessa máquina:

      • docker run -d -p 8080:80 --name httpserver nginx

      Neste comando, estamos mapeando a porta 80 no container Nginx para a porta 8080 no host Dockerizado para que possamos acessar a página padrão do Nginx de qualquer lugar.

      Depois que o container for construído, você poderá acessar a página padrão do Nginx apontando seu navegador para http://docker_machine_ip:8080.

      Enquanto o host Docker ainda estiver ativado (conforme visto pelo seu nome no prompt), você poderá listar as imagens nesse host:

      A saída inclui a imagem Nginx que você acabou de usar:

      • Output
      • nginx latest 71c43202b8ac 3 hours ago 109MB

      Você também pode listar os containers ativos ou em execução no host:

      Se o container Nginx que você executou nesta etapa for o único container ativo, a saída ficará assim:


      CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES d3064c237372 nginx "nginx -g 'daemon of…" About a minute ago Up About a minute>80/tcp httpserver

      Se você pretende criar containers em uma máquina remota, seu cliente Docker deve estar apontando para ele — isto é, deve ser a máquina ativa no terminal que você está usando. Caso contrário, você estará criando o container em sua máquina local. Novamente, deixe seu prompt de comando ser seu guia.

      O Docker Machine pode criar e gerenciar hosts remotos e também pode removê-los.

      Passo 9 – Removendo Hosts Docker

      Você pode usar o Docker Machine para remover um host Docker que você criou. Use o comando docker-machine rm para remover o host docker-01 que você criou:

      • docker-machine rm docker-01

      O Droplet é excluído junto com a chave SSH criada para ele. Liste os hosts novamente:

      Desta vez, você não verá o host docker-01 listado na saída. E se você criou apenas um host, você não verá saída alguma.

      Certifique-se de executar o comando docker-machine use -u para apontar seu daemon do Docker local de volta para sua máquina local.

      Passo 10 — Desativando o Relatório de Falhas (Opcinal)

      Por padrão, sempre que uma tentativa de provisionar um host Dockerizado usando o Docker Machine falha, ou o Docker Machine trava, algumas informações de diagnóstico são enviadas para uma conta Docker em Bugsnag. Se você não está confortável com isso, você pode desabilitar o relatório criando um arquivo vazio chamado no-error-report no diretório .docker/machine do seu computador local.

      Para criar o arquivo, digite:

      • touch ~/.docker/machine/no-error-report

      Verifique o arquivo em busca de mensagens de erro para falhas de provisionamento ou travamento do Docker Machine.


      Você instalou o Docker Machine e o usou para provisionar vários hosts Docker na DigitalOcean remotamente a partir do seu sistema local. A partir daqui, você deve ser capaz de provisionar quantos hosts Dockerizados forem necessários em sua conta DigitalOcean.

      Para mais informações sobre o Docker Machine, visite a página de documentação oficial. Os três scripts Bash baixados neste tutorial estão hospedados nessa página do GitHub.

      Por finid e Brian Hogan

      Source link

      How To Provision and Manage Remote Docker Hosts with Docker Machine on Ubuntu 18.04


      [Docker Machine](/) is a tool that makes it easy to provision and manage multiple Docker hosts remotely from your personal computer. Such servers are commonly referred to as Dockerized hosts and are used to run Docker containers.

      While Docker Machine can be installed on a local or a remote system, the most common approach is to install it on your local computer (native installation or virtual machine) and use it to provision Dockerized remote servers.

      Though Docker Machine can be installed on most Linux distributions as well as macOS and Windows, in this tutorial, you’ll install it on your local machine running Ubuntu 18.04 and use it to provision Dockerized DigitalOcean Droplets. If you don’t have a local Ubuntu 18.04 machine, you can follow these instructions on any Ubuntu 18.04 server.


      To follow this tutorial, you will need the following:

      • A local machine or server running Ubuntu 18.04 with Docker installed. See How To Install and Use Docker on Ubuntu 18.04 for instructions.
      • A DigitalOcean API token. If you don’t have one, generate it using this guide. When you generate a token, be sure that it has read-write scope. That is the default, so if you do not change any options while generating it, it will have read-write capabilities.

      Step 1 — Installing Docker Machine

      In order to use Docker Machine, you must first install it locally. On Ubuntu, this means downloading a handful of scripts from the official Docker repository on GitHub.

      To download and install the Docker Machine binary, type:

      • wget$(uname -s)-$(uname -m)

      The name of the file should be docker-machine-Linux-x86_64. Rename it to docker-machine to make it easier to work with:

      • mv docker-machine-Linux-x86_64 docker-machine

      Make it executable:

      Move or copy it to the /usr/local/bin directory so that it will be available as a system command:

      • sudo mv docker-machine /usr/local/bin

      Check the version, which will indicate that it's properly installed:

      You'll see output similar to this, displaying the version number and build:


      docker-machine version 0.15.0, build b48dc28d

      Docker Machine is installed. Let's install some additional helper tools to make Docker Machine easier to work with.

      Step 2 — Installing Additional Docker Machine Scripts

      There are three Bash scripts in the Docker Machine GitHub repository you can install to make working with the docker and docker-machine commands easier. When installed, these scripts provide command completion and prompt customization.

      In this step, you'll install these three scripts into the /etc/bash_completion.d directory on your local machine by downloading them directly from the Docker Machine GitHub repository.

      Note: Before downloading and installing a script from the internet in a system-wide location, you should inspect the script's contents first by viewing the source URL in your browser.

      The first script allows you to see the active machine in your prompt. This comes in handy when you are working with and switching between multiple Dockerized machines. The script is called docker-machine-prompt.bash. Download it

      • sudo wget -O /etc/bash_completion.d/docker-machine-prompt.bash

      To complete the installation of this file, you'll have to modify the value for the PS1 variable in your .bashrc file. The PS1 variable is a special shell variable used to modify the Bash command prompt. Open ~/.bashrc in your editor:

      Within that file, there are three lines that begin with PS1. They should look just like these:


      PS1='${debian_chroot:+($debian_chroot)}[33[01;32m]u@h[33[00m]:[33[01;34m]w[33[00m]$ '
      PS1='${debian_chroot:+($debian_chroot)}u@h:w$ '
      PS1="[e]0;${debian_chroot:+($debian_chroot)}u@h: wa]$PS1"

      For each line, insert $(__docker_machine_ps1 " [%s]") near the end, as shown in the following example:


      PS1='${debian_chroot:+($debian_chroot)}[33[01;32m]u@h[33[00m]:[33[01;34m]w[33[00m]$(__docker_machine_ps1 " [%s]")$ '
      PS1='${debian_chroot:+($debian_chroot)}u@h:w$(__docker_machine_ps1 " [%s]")$ '
      PS1="[e]0;${debian_chroot:+($debian_chroot)}u@h: wa]$(__docker_machine_ps1 " [%s]")$PS1"

      Save and close the file.

      The second script is called docker-machine-wrapper.bash. It adds a use subcommand to the docker-machine command, making it significantly easier to switch between Docker hosts. To download it, type:

      • sudo wget -O /etc/bash_completion.d/docker-machine-wrapper.bash

      The third script is called docker-machine.bash. It adds bash completion for docker-machine commands. Download it using:

      • sudo wget -O /etc/bash_completion.d/docker-machine.bash

      To apply the changes you've made so far, close, then reopen your terminal. If you're logged into the machine via SSH, exit the session and log in again, and you'll have command completion for the docker and docker-machine commands.

      Let's test things out by creating a new Docker host with Docker Machine.

      Step 3 — Provisioning a Dockerized Host Using Docker Machine

      Now that you have Docker and Docker Machine running on your local machine, you can provision a Dockerized Droplet on your DigitalOcean account using Docker Machine's docker-machine create command. If you've not done so already, assign your DigitalOcean API token to an environment variable:

      • export DOTOKEN=your-api-token

      NOTE: This tutorial uses DOTOKEN as the bash variable for the DO API token. The variable name does not have to be DOTOKEN, and it does not have to be in all caps.

      To make the variable permanent, put it in your ~/.bashrc file. This step is optional, but it is necessary if you want to the value to persist across shell sessions.

      Open that file with nano:

      Add this line to the file:


      export DOTOKEN=your-api-token

      To activate the variable in the current terminal session, type:

      To call the docker-machine create command successfully you must specify the driver you wish to use, as well as a machine name. The driver is the adapter for the infrastructure you're going to create. There are drivers for cloud infrastructure providers, as well as drivers for various virtualization platforms.

      We'll use the digitalocean driver. Depending on the driver you select, you'll need to provide additional options to create a machine. The digitalocean driver requires the API token (or the variable that evaluates to it) as its argument, along with the name for the machine you want to create.

      To create your first machine, type this command to create a DigitalOcean Droplet called docker-01:

      • docker-machine create --driver digitalocean --digitalocean-access-token $DOTOKEN docker-01

      You'll see this output as Docker Machine creates the Droplet:


      ... Installing Docker... Copying certs to the local machine directory... Copying certs to the remote machine... Setting Docker configuration on the remote daemon... Checking connection to Docker... Docker is up and running! To see how to connect your Docker Client to the Docker Engine running on this virtual machine, run: docker-machine env ubuntu1804-docker

      Docker Machine creates an SSH key pair for the new host so it can access the server remotely. The Droplet is provisioned with an operating system and Docker is installed. When the command is complete, your Docker Droplet is up and running.

      To see the newly-created machine from the command line, type:

      The output will be similar to this, indicating that the new Docker host is running:


      NAME ACTIVE DRIVER STATE URL SWARM DOCKER ERRORS docker-01 - digitalocean Running tcp:// v18.06.1-ce

      Now let's look at how to specify the operating system when we create a machine.

      Step 4 — Specifying the Base OS and Droplet Options When Creating a Dockerized Host

      By default, the base operating system used when creating a Dockerized host with Docker Machine is supposed to be the latest Ubuntu LTS. However, at the time of this publication, the docker-machine create command is still using Ubuntu 16.04 LTS as the base operating system, even though Ubuntu 18.04 is the latest LTS edition. So if you need to run Ubuntu 18.04 on a recently-provisioned machine, you'll have to specify Ubuntu along with the desired version by passing the --digitalocean-image flag to the docker-machine create command.

      For example, to create a machine using Ubuntu 18.04, type:

      • docker-machine create --driver digitalocean --digitalocean-image ubuntu-18-04-x64 --digitalocean-access-token $DOTOKEN docker-ubuntu-1804

      You're not limited to a version of Ubuntu. You can create a machine using any operating system supported on DigitalOcean. For example, to create a machine using Debian 8, type:

      • docker-machine create --driver digitalocean --digitalocean-image debian-8-x64 --digitalocean-access-token $DOTOKEN docker-debian

      To provision a Dockerized host using CentOS 7 as the base OS, specify centos-7-0-x86 as the image name, like so:

      • docker-machine create --driver digitalocean --digitalocean-image centos-7-0-x64 --digitalocean-access-token $DOTOKEN docker-centos7

      The base operating system is not the only choice you have. You can also specify the size of the Droplet. By default, it is the smallest Droplet, which has 1 GB of RAM, a single CPU, and a 25 GB SSD.

      Find the size of the Droplet you want to use by looking up the corresponding slug in the DigitalOcean API documentation.

      For example, to provision a machine with 2 GB of RAM, two CPUs, and a 60 GB SSD, use the slug s-2vcpu-2gb:

      • docker-machine create --driver digitalocean --digitalocean-size s-2vcpu-2gb --digitalocean-access-token $DOTOKEN docker-03

      To see all the flags specific to creating a Docker Machine using the DigitalOcean driver, type:

      • docker-machine create --driver digitalocean -h

      Tip: If you refresh the Droplet page of your DigitalOcean dashboard, you will see the new machines you created using the docker-machine command.

      Now let's explore some of the other Docker Machine commands.

      Step 5 — Executing Additional Docker Machine Commands

      You've seen how to provision a Dockerized host using the create subcommand, and how to list the hosts available to Docker Machine using the ls subcommand. In this step, you'll learn a few more useful subcommands.

      To obtain detailed information about a Dockerized host, use the inspect subcommand, like so:

      • docker-machine inspect docker-01

      The output includes lines like the ones in the following output. The Image line reveals the version of the Linux distribution used and the Size line indicates the size slug:


      ... { "ConfigVersion": 3, "Driver": { "IPAddress": "", "MachineName": "docker-01", "SSHUser": "root", "SSHPort": 22, ... "Image": "ubuntu-16-04-x64", "Size": "s-1vcpu-1gb", ... }, ---

      To print the connection configuration for a host, type:

      • docker-machine config docker-01

      The output will be similar to this:


      --tlsverify --tlscacert="/home/kamit/.docker/machine/certs/ca.pem" --tlscert="/home/kamit/.docker/machine/certs/cert.pem" --tlskey="/home/kamit/.docker/machine/certs/key.pem" -H=tcp://

      The last line in the output of the docker-machine config command reveals the IP address of the host, but you can also get that piece of information by typing:

      • docker-machine ip docker-01

      If you need to power down a remote host, you can use docker-machine to stop it:

      • docker-machine stop docker-01

      Verify that it is stopped:

      The output shows that the status of the machine has changed:


      NAME ACTIVE DRIVER STATE URL SWARM DOCKER ERRORS docker-01 - digitalocean Stopped Unknown

      To start it again, use the start subcommand:

      • docker-machine start docker-01

      Then review its status again:

      You will see that the STATE is now set Running for the host:


      NAME ACTIVE DRIVER STATE URL SWARM DOCKER ERRORS docker-01 - digitalocean Running tcp:// v18.06.1-ce

      Next let's look at how to interact with the remote host using SSH.

      Step 6 — Executing Commands on a Dockerized Host via SSH

      At this point, you've been getting information about your machines, but you can do more than that. For example, you can execute native Linux commands on a Docker host by using the ssh subcommand of docker-machine from your local system. This section explains how to perform ssh commands via docker-machine as well as how to open an SSH session to a Dockerized host.

      Assuming that you've provisioned a machine with Ubuntu as the operating system, execute the following command from your local system to update the package database on the Docker host:

      • docker-machine ssh docker-01 apt-get update

      You can even apply available updates using:

      • docker-machine ssh docker-01 apt-get upgrade

      Not sure what kernel your remote Docker host is using? Type the following:

      • docker-machine ssh docker-01 uname -r

      Finally, you can log in to the remote host with the docker machine ssh command:

      docker-machine ssh docker-01

      You'll be logged in as the root user and you'll see something similar to the following:

      Welcome to Ubuntu 16.04.5 LTS (GNU/Linux 4.4.0-131-generic x86_64)
       * Documentation:
       * Management:
       * Support:
        Get cloud support with Ubuntu Advantage Cloud Guest:

      14 packages can be updated.
      10 updates are security updates.

      Log out by typing exit to return to your local machine.

      Next, we'll direct Docker's commands at our remote host.

      Step 7 — Activating a Dockerized Host

      Activating a Docker host connects your local Docker client to that system, which makes it possible to run normal docker commands on the remote system.

      First, use Docker Machine to create a new Docker host called docker-ubuntu using Ubuntu 18.04:

      • docker-machine create --driver digitalocean --digitalocean-image ubuntu-18-04-x64 --digitalocean-access-token $DOTOKEN docker-ubuntu

      To activate a Docker host, type the following command:

      • eval $(docker-machine env machine-name)

      Alternatively, you can activate it by using this command:

      • docker-machine use machine-name

      Tip When working with multiple Docker hosts, the docker-machine use command is the easiest method of switching from one to the other.

      After typing any of these commands, your prompt will change to indicate that your Docker client is pointing to the remote Docker host. It will take this form. The name of the host will be at the end of the prompt:

      username@localmachine:~ [docker-01]$

      Now any docker command you type at this command prompt will be executed on that remote host.

      Execute docker-machine ls again:

      You'll see an asterisk under the ACTIVE column for docker-01:


      NAME ACTIVE DRIVER STATE URL SWARM DOCKER ERRORS docker-01 * digitalocean Running tcp:// v18.06.1-ce

      To exit from the remote Docker host, type the following:

      Your prompt will no longer show the active host.

      Now let's create containers on the remote machine.

      Step 8 — Creating Docker Containers on a Remote Dockerized Host

      So far, you have provisioned a Dockerized Droplet on your DigitalOcean account and you've activated it — that is, your Docker client is pointing to it. The next logical step is to spin up containers on it. As an example, let's try running the official Nginx container.

      Use docker-machine use to select your remote machine:

      • docker-machine use docker-01

      Now execute this command to run an Nginx container on that machine:

      • docker run -d -p 8080:80 --name httpserver nginx

      In this command, we're mapping port 80 in the Nginx container to port 8080 on the Dockerized host so that we can access the default Nginx page from anywhere.

      Once the container builds, you will be able to access the default Nginx page by pointing your web browser to http://docker_machine_ip:8080.

      While the Docker host is still activated (as seen by its name in the prompt), you can list the images on that host:

      The output includes the Nginx image you just used:


      REPOSITORY TAG IMAGE ID CREATED SIZE nginx latest 71c43202b8ac 3 hours ago 109MB

      You can also list the active or running containers on the host:

      If the Nginx container you ran in this step is the only active container, the output will look like this:


      CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES d3064c237372 nginx "nginx -g 'daemon of…" About a minute ago Up About a minute>80/tcp httpserver

      If you intend to create containers on a remote machine, your Docker client must be pointing to it — that is, it must be the active machine in the terminal that you're using. Otherwise you'll be creating the container on your local machine. Again, let your command prompt be your guide.

      Docker Machine can create and manage remote hosts, and it can also remove them.

      Step 9 – Removing Docker Hosts

      You can use Docker Machine to remove a Docker host you've created. Use the docker-machine rm command to remove the docker-01 host you created:

      • docker-machine rm docker-01

      The Droplet is deleted along with the SSH key created for it. List the hosts again:

      This time, you won't see the docker-01 host listed in the output. And if you've only created one host, you won't see any output at all.

      Be sure to execute the command docker-machine use -u to point your local Docker daemon back to your local machine.

      Step 10 — Disabling Crash Reporting (Optional)

      By default, whenever an attempt to provision a Dockerized host using Docker Machine fails, or Docker Machine crashes, some diagnostic information is sent to a Docker account on Bugsnag. If you're not comfortable with this, you can disable the reporting by creating an empty file called no-error-report in your local computer's .docker/machine directory.

      To create the file, type:

      • touch ~/.docker/machine/no-error-report

      Check the file for error messages if provisioning fails or Docker Machine crashes.


      You've installed Docker Machine and used it to provision multiple Docker hosts on DigitalOcean remotely from your local system. From here you should be able to provision as many Dockerized hosts on your DigitalOcean account as you need.

      For more on Docker Machine, visit the official documentation page. The three Bash scripts downloaded in this tutorial are hosted on this GitHub page.

      Source link