Todos os produtos
Search
Central de documentação

Elastic Compute Service:Install MySQL on a Linux instance

Última atualização: Jul 03, 2026

Este tópico descreve como implantar manualmente uma versão específica do banco de dados MySQL em uma instância ECS Linux.

Pré-requisitos

  • A instância ECS deve ter um endereço IP público atribuído automaticamente ou um Elastic IP Address (EIP) associado. Para obter instruções sobre como ativar a largura de banda pública, consulte Ativar largura de banda pública.

  • O grupo de segurança da instância ECS precisa ter uma regra de entrada que permita tráfego na porta 22. Para mais informações, consulte Adicionar uma regra de grupo de segurança.

Implantar o MySQL

Alibaba Cloud Linux 3

  1. Conecte-se à instância ECS. Para mais informações, consulte Fazer login em uma instância Linux usando o Workbench.

  2. Instale o banco de dados MySQL.

    # Install compat-openssl10 for compatibility with older OpenSSL libraries.
    sudo yum install -y compat-openssl10
    # Add the official MySQL repository.
    sudo rpm -Uvh https://repo.mysql.com/mysql84-community-release-el8-1.noarch.rpm
    # Install the MySQL service.
    sudo dnf install -y mysql-server
    # Start the MySQL service and enable it to start on boot.
    sudo systemctl start mysqld
    sudo systemctl enable mysqld
  3. Obtenha a senha temporária de root.

    echo $(PASSWORD=$(sudo grep 'temporary password' /var/log/mysqld.log); PASSWORD=${PASSWORD##* }; echo $PASSWORD)
  4. Execute o comando a seguir para iniciar o assistente de instalação segura do MySQL.

    sudo mysql_secure_installation
    1. Insira a senha temporária do usuário root.

      Nota

      A senha não é exibida durante a digitação. Certifique-se de digitá-la corretamente.

      Securing the MySQL server deployment.
      Enter password for user root:
    2. Quando receber o aviso de que a senha de root expirou, defina uma nova senha para o usuário root. Será necessário inserir a nova senha duas vezes.

      Importante

      A política de senhas exige pelo menos 8 caracteres, contendo no mínimo uma letra maiúscula, uma letra minúscula, um dígito e um caractere especial.

      The existing password for the user account root has expired. Please set a new password.
      New password:
      Re-enter new password:
    3. Após alterar a senha do root, insira n para pular a alteração da senha novamente.

      Change the password for root ? (Press y|Y for Yes, any other key for No) :
    4. No prompt Remove anonymous users?, insira y.

      Nota

      Remover usuários anônimos ajuda a impedir o acesso ao servidor MySQL sem uma conta de usuário.

      By default, a MySQL installation has an anonymous user,
      allowing anyone to log into MySQL without having to have
      a user account created for them. This is intended only for
      testing, and to make the installation go a bit smoother.
      You should remove them before moving into a production
      environment.
      Remove anonymous users? (Press y|Y for Yes, any other key for No) :
    5. No prompt Disallow root login remotely?, insira y para proibir o login remoto do usuário root do MySQL.

      Nota

      Caso precise permitir o login remoto do root por algum motivo específico, pressione qualquer tecla diferente de Y.

      Normally, root should only be allowed to connect from
      'localhost'. This ensures that someone cannot guess at
      the root password from the network.
      Disallow root login remotely? (Press y|Y for Yes, any other key for No) :
    6. No prompt Remove test database and access to it?, insira y para remover o banco de dados padrão test.

      By default, MySQL comes with a database named 'test' that
      anyone can access. This is also intended only for testing,
      and should be removed before moving into a production
      environment.
      Remove test database and access to it? (Press y|Y for Yes, any other key for No) :
    7. No prompt Reload privilege tables now?, insira y para aplicar as alterações.

      Reloading the privilege tables will ensure that all changes
      made so far will take effect immediately.
      Reload privilege tables now? (Press y|Y for Yes, any other key for No) :

Alibaba Cloud Linux 2

  1. Conecte-se à instância ECS. Para mais informações, consulte Fazer login em uma instância Linux usando o Workbench.

  2. Instale o banco de dados MySQL.

    # Add the official MySQL repository.
    sudo rpm -Uvh https://repo.mysql.com/mysql84-community-release-el7-1.noarch.rpm
    # Install the MySQL service.
    sudo yum install -y mysql-server
    # Start the MySQL service and enable it to start on boot.
    sudo systemctl start mysqld
    sudo systemctl enable mysqld
  3. Obtenha a senha temporária de root.

    echo $(PASSWORD=$(sudo grep 'temporary password' /var/log/mysqld.log); PASSWORD=${PASSWORD##* }; echo $PASSWORD)
  4. Execute o comando a seguir para iniciar o assistente de instalação segura do MySQL.

    sudo mysql_secure_installation
    1. Insira a senha temporária do usuário root.

      Nota

      A senha não é exibida durante a digitação. Certifique-se de digitá-la corretamente.

      Securing the MySQL server deployment.
      Enter password for user root:
    2. Quando receber o aviso de que a senha de root expirou, defina uma nova senha para o usuário root. Será necessário inserir a nova senha duas vezes.

      Importante

      A política de senhas exige pelo menos 8 caracteres, contendo no mínimo uma letra maiúscula, uma letra minúscula, um dígito e um caractere especial.

      The existing password for the user account root has expired. Please set a new password.
      New password:
      Re-enter new password:
    3. Após alterar a senha do root, insira n para pular a alteração da senha novamente.

      Change the password for root ? (Press y|Y for Yes, any other key for No) :
    4. No prompt Remove anonymous users?, insira y.

      Nota

      Remover usuários anônimos ajuda a impedir o acesso ao servidor MySQL sem uma conta de usuário.

      By default, a MySQL installation has an anonymous user,
      allowing anyone to log into MySQL without having to have
      a user account created for them. This is intended only for
      testing, and to make the installation go a bit smoother.
      You should remove them before moving into a production
      environment.
      Remove anonymous users? (Press y|Y for Yes, any other key for No) :
    5. No prompt Disallow root login remotely?, insira y para proibir o login remoto do usuário root do MySQL.

      Nota

      Caso precise permitir o login remoto do root por algum motivo específico, pressione qualquer tecla diferente de Y.

      Normally, root should only be allowed to connect from
      'localhost'. This ensures that someone cannot guess at
      the root password from the network.
      Disallow root login remotely? (Press y|Y for Yes, any other key for No) :
    6. No prompt Remove test database and access to it?, insira y para remover o banco de dados padrão test.

      By default, MySQL comes with a database named 'test' that
      anyone can access. This is also intended only for testing,
      and should be removed before moving into a production
      environment.
      Remove test database and access to it? (Press y|Y for Yes, any other key for No) :
    7. No prompt Reload privilege tables now?, insira y para aplicar as alterações.

      Reloading the privilege tables will ensure that all changes
      made so far will take effect immediately.
      Reload privilege tables now? (Press y|Y for Yes, any other key for No) :

CentOS 8

  1. Conecte-se à instância ECS. Para mais informações, consulte Fazer login em uma instância Linux usando o Workbench.

  2. Instale o banco de dados MySQL.

    # Add the official MySQL repository.
    sudo rpm -Uvh https://repo.mysql.com/mysql84-community-release-el8-1.noarch.rpm
    # Install the MySQL service.
    sudo dnf install -y mysql-server
    # Start the MySQL service and enable it to start on boot.
    sudo systemctl start mysqld
    sudo systemctl enable mysqld
  3. Execute o comando a seguir para iniciar o assistente de instalação segura do MySQL.

    sudo mysql_secure_installation
    1. No prompt Would you like to setup VALIDATE PASSWORD component?, insira y para ativar o componente VALIDATE PASSWORD.

      Securing the MySQL server deployment.
      Connecting to MySQL using a blank password.
      VALIDATE PASSWORD COMPONENT can be used to test passwords
      and improve security. It checks the strength of password
      and allows the users to set only those passwords which are
      secure enough. Would you like to setup VALIDATE PASSWORD component?
      Press y|Y for Yes, any other key for No:
    2. Insira 2 para definir o nível da política de senhas como STRONG. Essa política exige senhas com pelo menos 8 caracteres, contendo números, letras maiúsculas e minúsculas, caracteres especiais e que não sejam baseadas em um arquivo de dicionário.

      There are three levels of password validation policy:
      LOW    Length >= 8
      MEDIUM Length >= 8, numeric, mixed case, and special characters
      STRONG Length >= 8, numeric, mixed case, special characters and dictionary                  file
      Please enter 0 = LOW, 1 = MEDIUM and 2 = STRONG:
    3. Defina uma nova senha para o usuário root. Será necessário inserir a nova senha duas vezes.

      New password:
      
      Re-enter new password:
      
      Estimated strength of the password: 100
      Importante

      A política de senhas exige pelo menos 8 caracteres, contendo no mínimo uma letra maiúscula, uma letra minúscula, um dígito e um caractere especial.

    4. No prompt Do you wish to continue with the password provided?, insira y.

      Do you wish to continue with the password provided?(Press y|Y for Yes, any other key for No) :
    5. No prompt Remove anonymous users?, insira y.

      Nota

      Remover usuários anônimos ajuda a impedir o acesso ao servidor MySQL sem uma conta de usuário.

      By default, a MySQL installation has an anonymous user,
      allowing anyone to log into MySQL without having to have
      a user account created for them. This is intended only for
      testing, and to make the installation go a bit smoother.
      You should remove them before moving into a production
      environment.
      Remove anonymous users? (Press y|Y for Yes, any other key for No) :
    6. No prompt Disallow root login remotely?, insira y para proibir o login remoto do usuário root do MySQL.

      Nota

      Caso precise permitir o login remoto do root por algum motivo específico, pressione qualquer tecla diferente de Y.

      Normally, root should only be allowed to connect from
      'localhost'. This ensures that someone cannot guess at
      the root password from the network.
      Disallow root login remotely? (Press y|Y for Yes, any other key for No) :
    7. No prompt Remove test database and access to it?, insira y para remover o banco de dados padrão test.

      By default, MySQL comes with a database named 'test' that
      anyone can access. This is also intended only for testing,
      and should be removed before moving into a production
      environment.
      Remove test database and access to it? (Press y|Y for Yes, any other key for No) :
    8. No prompt Reload privilege tables now?, insira y para aplicar as alterações.

      Reloading the privilege tables will ensure that all changes
      made so far will take effect immediately.
      Reload privilege tables now? (Press y|Y for Yes, any other key for No) :

CentOS 7

  1. Conecte-se à instância ECS. Para mais informações, consulte Fazer login em uma instância Linux usando o Workbench.

  2. Instale o banco de dados MySQL.

    # Add the official MySQL repository.
    sudo rpm -Uvh https://repo.mysql.com/mysql84-community-release-el7-1.noarch.rpm
    # Install the MySQL service.
    sudo yum install -y mysql-server
    # Start the MySQL service and enable it to start on boot.
    sudo systemctl start mysqld
    sudo systemctl enable mysqld
  3. Obtenha a senha temporária de root.

    echo $(PASSWORD=$(sudo grep 'temporary password' /var/log/mysqld.log); PASSWORD=${PASSWORD##* }; echo $PASSWORD)
  4. Execute o comando a seguir para iniciar o assistente de instalação segura do MySQL.

    sudo mysql_secure_installation
    1. Insira a senha temporária do usuário root.

      Nota

      A senha não é exibida durante a digitação. Certifique-se de digitá-la corretamente.

      Securing the MySQL server deployment.
      Enter password for user root:
    2. Quando receber o aviso de que a senha de root expirou, defina uma nova senha para o usuário root. Será necessário inserir a nova senha duas vezes.

      Importante

      A política de senhas exige pelo menos 8 caracteres, contendo no mínimo uma letra maiúscula, uma letra minúscula, um dígito e um caractere especial.

      The existing password for the user account root has expired. Please set a new password.
      New password:
      Re-enter new password:
    3. Após alterar a senha do root, insira n para pular a alteração da senha novamente.

      Change the password for root ? (Press y|Y for Yes, any other key for No) :
    4. No prompt Remove anonymous users?, insira y.

      Nota

      Remover usuários anônimos ajuda a impedir o acesso ao servidor MySQL sem uma conta de usuário.

      By default, a MySQL installation has an anonymous user,
      allowing anyone to log into MySQL without having to have
      a user account created for them. This is intended only for
      testing, and to make the installation go a bit smoother.
      You should remove them before moving into a production
      environment.
      Remove anonymous users? (Press y|Y for Yes, any other key for No) :
    5. No prompt Disallow root login remotely?, insira y para proibir o login remoto do usuário root do MySQL.

      Nota

      Caso precise permitir o login remoto do root por algum motivo específico, pressione qualquer tecla diferente de Y.

      Normally, root should only be allowed to connect from
      'localhost'. This ensures that someone cannot guess at
      the root password from the network.
      Disallow root login remotely? (Press y|Y for Yes, any other key for No) :
    6. No prompt Remove test database and access to it?, insira y para remover o banco de dados padrão test.

      By default, MySQL comes with a database named 'test' that
      anyone can access. This is also intended only for testing,
      and should be removed before moving into a production
      environment.
      Remove test database and access to it? (Press y|Y for Yes, any other key for No) :
    7. No prompt Reload privilege tables now?, insira y para aplicar as alterações.

      Reloading the privilege tables will ensure that all changes
      made so far will take effect immediately.
      Reload privilege tables now? (Press y|Y for Yes, any other key for No) :

Ubuntu/Debian

  1. Conecte-se à instância ECS. Para mais informações, consulte Fazer login em uma instância Linux usando o Workbench.

  2. Execute o comando a seguir para atualizar a lista de pacotes.

    sudo apt-get update
  3. Instale o repositório APT do MySQL.

    # Download the APT configuration package.
    sudo wget https://dev.mysql.com/get/mysql-apt-config_0.8.33-1_all.deb
    # Use the dpkg command to install the downloaded MySQL APT configuration package.
    sudo dpkg -i mysql-apt-config_0.8.33-1_all.deb
    1. (Opcional) Se o script mysql-apt-config detectar que a versão do seu sistema operacional não tem suporte oficial, uma interface será exibida. Selecione a versão suportada mais compatível para continuar.

      Nota

      Para encontrar o codinome do seu sistema, consulte FAQ.

      Configuring mysql-apt-config
      The detected system (ubuntu bionic) is not supported by MySQL. If you believe the platform is compatible with one of the supported systems, one of the corresponding repositories may be selected.
      Add repository to unsupported system?
                                  ubuntu lunar
                                  ubuntu focal
                                  ubuntu jammy
                                  ubuntu noble
                                  ubuntu oracular
                                  debian bookworm
                                  abort
                                     <Ok>
    2. A página de configuração lista todos os componentes a serem instalados, incluindo MySQL Server, Client e Tools. Verifique a versão e os componentes, use as setas do teclado para navegar até Ok e pressione Enter.

      Configuring mysql-apt-config
      The MySQL APT Repository features MySQL Server along with a variety of components. You may select the desired products to install and update from the official MySQL Repository, and also select the associated version series.
      Select "Ok" to save the configuration, and then execute "apt update" to load the selected package list. This configuration can be updated later, depending on your needs.
      Which MySQL product do you wish to configure?
          MySQL Server & Cluster (Currently selected: mysql-8.4-lts)
          MySQL Connectors (Currently selected: Enabled)
          Ok
                                    <Ok>
  4. Instale o servidor MySQL.

    Importante

    Durante a instalação, a caixa de diálogo Configuring mysql-community-server solicitará que você defina uma senha para o usuário root do MySQL. A política de senhas exige pelo menos 8 caracteres, incluindo uma letra maiúscula, uma letra minúscula, um dígito e um caractere especial. No campo Enter root password, insira sua senha e selecione Ok. Na próxima caixa de diálogo Configuring mysql-community-server, reinsira a senha no campo Re-enter root password e selecione Ok para confirmar. Se deixar o campo de senha em branco, a autenticação por socket UNIX será ativada. Mantenha essa senha segura.

    # Update the package list.
    sudo apt update
    # Install the MySQL server.
    sudo apt install -y mysql-server
    # Start the MySQL service.
    sudo systemctl start mysql
    # Check the service status.
    sudo systemctl status mysql
    # Enable the service to start on boot.
    sudo systemctl enable mysql
  5. Execute o comando a seguir para iniciar o assistente de instalação segura do MySQL.

    sudo mysql_secure_installation
    1. Insira a senha do usuário root.

    2. No prompt Would you like to setup VALIDATE PASSWORD component?, insira y para ativar o componente VALIDATE PASSWORD.

      Securing the MySQL server deployment.
      Connecting to MySQL using a blank password.
      VALIDATE PASSWORD COMPONENT can be used to test passwords
      and improve security. It checks the strength of password
      and allows the users to set only those passwords which are
      secure enough. Would you like to setup VALIDATE PASSWORD component?
      Press y|Y for Yes, any other key for No:
    3. Insira 2 para definir o nível da política de senhas como STRONG. Essa política exige senhas com pelo menos 8 caracteres, contendo números, letras maiúsculas e minúsculas, caracteres especiais e que não sejam baseadas em um arquivo de dicionário.

      There are three levels of password validation policy:
      LOW    Length >= 8
      MEDIUM Length >= 8, numeric, mixed case, and special characters
      STRONG Length >= 8, numeric, mixed case, special characters and dictionary                  file
      Please enter 0 = LOW, 1 = MEDIUM and 2 = STRONG:
    4. Como a senha de root foi definida durante a etapa de instalação via apt, é possível pular a alteração agora. Insira n para continuar.

      Nota

      Caso precise alterar a senha do usuário root, insira y.

    5. No prompt Remove anonymous users?, insira y.

      Nota

      Remover usuários anônimos ajuda a impedir o acesso ao servidor MySQL sem uma conta de usuário.

      By default, a MySQL installation has an anonymous user,
      allowing anyone to log into MySQL without having to have
      a user account created for them. This is intended only for
      testing, and to make the installation go a bit smoother.
      You should remove them before moving into a production
      environment.
      Remove anonymous users? (Press y|Y for Yes, any other key for No) :
    6. No prompt Disallow root login remotely?, insira y para proibir o login remoto do usuário root do MySQL.

      Nota

      Caso precise permitir o login remoto do root por algum motivo específico, pressione qualquer tecla diferente de Y.

      Normally, root should only be allowed to connect from
      'localhost'. This ensures that someone cannot guess at
      the root password from the network.
      Disallow root login remotely? (Press y|Y for Yes, any other key for No) :
    7. No prompt Remove test database and access to it?, insira y para remover o banco de dados padrão test.

      By default, MySQL comes with a database named 'test' that
      anyone can access. This is also intended only for testing,
      and should be removed before moving into a production
      environment.
      Remove test database and access to it? (Press y|Y for Yes, any other key for No) :
    8. No prompt Reload privilege tables now?, insira y para aplicar as alterações.

      Reloading the privilege tables will ensure that all changes
      made so far will take effect immediately.
      Reload privilege tables now? (Press y|Y for Yes, any other key for No) :

Adicionar um usuário remoto do MySQL

  1. Conecte-se à instância ECS. Para mais informações, consulte Fazer login em uma instância Linux usando o Workbench.

  2. Verifique se o grupo de segurança da instância possui uma regra de entrada que permita tráfego na porta 3306. Se utilizar uma porta diferente, ajuste as configurações do grupo de segurança adequadamente. Para mais informações, consulte Adicionar uma regra de grupo de segurança.

  3. Execute o comando a seguir para criar um usuário e conceder permissões de acesso remoto a todos os bancos de dados MySQL.

    Importante
    • Substitua <username> pelo nome de usuário que deseja criar.

    • Substitua <password> pela senha do usuário MySQL. A senha deve ter pelo menos 8 caracteres e incluir uma letra maiúscula, uma letra minúscula, um dígito e um caractere especial.

    # After you run the command, enter the password for the root user.
    sudo mysql -uroot -p \
    -e "CREATE USER '<username>'@'%' IDENTIFIED BY '<password>';" \
    -e "GRANT ALL PRIVILEGES ON *.* TO '<username>'@'%' WITH GRANT OPTION;" \
    -e "FLUSH PRIVILEGES;"
  4. Verifique a conexão utilizando as credenciais do novo usuário.

    # Replace  with the username of the user that you created. After you run the command, enter the password for the new user.
    sudo mysql -u<username> -p

Referências

FAQ