Como hospedar um site estático no Google App Engine
Mantenha tudo organizado com as coleções
Salve e categorize o conteúdo com base nas suas preferências.
ID da região
O REGION_ID é um código abreviado que o Google atribui
com base na região que você selecionou ao criar o aplicativo. O código não
corresponde a um país ou estado, ainda que alguns IDs de região sejam semelhantes
aos códigos de país e estado geralmente usados. Para apps criados após
fevereiro de 2020, o REGION_ID.r está incluído nos
URLs do App Engine. Para apps existentes criados antes dessa data, o
ID da região é opcional no URL.
É possível usar o App Engine para hospedar um site estático. As páginas da Web estáticas
podem conter tecnologias de cliente, como HTML, CSS e JavaScript. Hospedar
o site estático no App Engine pode custar menos do que usar um provedor de hospedagem
tradicional, porque o App Engine oferece um nível gratuito.
Os sites no App Engine são hospedados no subdomínio REGION_ID.r.appspot.com, como [my-project-id].uc.r.appspot.com. Depois de implantar o
site, é possível mapear o próprio nome de domínio para o site hospedado pelo App Engine.
Antes de começar
Para hospedar o site no App Engine:
Crie um novo projeto do Console do Google Cloud ou recupere o ID do projeto
atual para usar:
Como listar os IDs de projetos do Console do Google Cloud
Na linha de comando, execute:
gcloud projects list
Como criar um site a ser hospedado no Google App Engine
Estrutura básica do projeto
Este guia usa a seguinte estrutura no projeto:
app.yaml: define as configurações do aplicativo do App Engine.
www/: diretório para armazenar todos os arquivos estáticos, como HTML, CSS, imagens e JavaScript.
css/: diretório para armazenar folhas de estilo.
style.css: folha de estilo básica que formata a aparência do seu site.
images/: diretório opcional para armazenar imagens.
index.html: arquivo HTML que exibe o conteúdo do seu site.
js/: diretório opcional para armazenar arquivos JavaScript.
Outros diretórios de assets.
Como criar o arquivo app.yaml
O app.yaml é um arquivo de configuração que informa ao App Engine como
mapear URLs para os arquivos estáticos. Nas etapas a seguir, serão adicionados gerenciadores
que vão carregar www/index.html quando alguém visitar seu site, e todos os arquivos
estáticos serão armazenados e chamados no diretório www.
Crie o arquivo app.yaml no diretório raiz do aplicativo:
Crie um diretório que tenha o mesmo nome do ID do projeto. Encontre o ID do projeto no Console.
No diretório recém criado, crie um arquivo chamado app.yaml.
Edite o arquivo app.yaml e adicione o elemento dos gerenciadores com base nos requisitos do seu
site. Por exemplo, o arquivo app.yaml para o ambiente de execução do Python pode ser criado da seguinte maneira:
Ao implantar os arquivos do aplicativo, o site será enviado para o App Engine. Para implantar o aplicativo, execute o seguinte comando no diretório raiz do aplicativo em que o arquivo app.yaml está localizado:
gcloud app deploy
Sinalizações opcionais:
Inclua a flag --project para especificar um ID de projeto alternativo do console do Google Cloud para o que você inicializou como padrão na CLI gcloud. Exemplo: --project [YOUR_PROJECT_ID]
Inclua a flag -v para especificar um ID de versão. Caso contrário, vai ser gerado
um para você. Exemplo: -v [YOUR_VERSION_ID]
Saiba mais sobre a implantação do aplicativo na linha de comando em
Implantar o aplicativo.
Ver o aplicativo
Para iniciar seu navegador e ver o aplicativo em https://PROJECT_ID.REGION_ID.r.appspot.com, execute o comando a seguir:
[[["Fácil de entender","easyToUnderstand","thumb-up"],["Meu problema foi resolvido","solvedMyProblem","thumb-up"],["Outro","otherUp","thumb-up"]],[["Difícil de entender","hardToUnderstand","thumb-down"],["Informações incorretas ou exemplo de código","incorrectInformationOrSampleCode","thumb-down"],["Não contém as informações/amostras de que eu preciso","missingTheInformationSamplesINeed","thumb-down"],["Problema na tradução","translationIssue","thumb-down"],["Outro","otherDown","thumb-down"]],["Última atualização 2025-04-21 UTC."],[[["\u003cp\u003eApp Engine can host static websites, including HTML, CSS, and JavaScript, potentially offering cost savings compared to traditional hosting due to its free tier.\u003c/p\u003e\n"],["\u003cp\u003eEach App Engine application is assigned a \u003ccode\u003eREGION_ID\u003c/code\u003e upon creation, which is included in the application's URL, formatted as \u003ccode\u003eREGION_ID.r.appspot.com\u003c/code\u003e.\u003c/p\u003e\n"],["\u003cp\u003eTo host a website, you need to create an \u003ccode\u003eapp.yaml\u003c/code\u003e configuration file to map URLs to your static files, and have a project directory to store the static files, including an \u003ccode\u003eindex.html\u003c/code\u003e file for the home page.\u003c/p\u003e\n"],["\u003cp\u003eDeploying the website involves using the \u003ccode\u003egcloud app deploy\u003c/code\u003e command from the application's root directory to upload the website content to App Engine.\u003c/p\u003e\n"],["\u003cp\u003eThe Region ID can be used to view your website in your browser by using the command \u003ccode\u003egcloud app browse\u003c/code\u003e, at \u003ccode\u003ehttps://PROJECT_ID.REGION_ID.r.appspot.com\u003c/code\u003e.\u003c/p\u003e\n"]]],[],null,["# Hosting a static website on App Engine\n\n\u003cbr /\u003e\n\n\u003cbr /\u003e\n\n\n### Region ID\n\nThe \u003cvar translate=\"no\"\u003eREGION_ID\u003c/var\u003e is an abbreviated code that Google assigns\nbased on the region you select when you create your app. The code does not\ncorrespond to a country or province, even though some region IDs may appear\nsimilar to commonly used country and province codes. For apps created after\nFebruary 2020, \u003cvar translate=\"no\"\u003eREGION_ID\u003c/var\u003e`.r` is included in\nApp Engine URLs. For existing apps created before this date, the\nregion ID is optional in the URL.\n\nLearn more\n[about region IDs](/appengine/docs/standard/python/how-requests-are-routed#region-id). \nOK\n\nYou can use App Engine to host a static website. Static web pages\ncan contain client-side technologies such as HTML, CSS, and JavaScript. Hosting\nyour static site on App Engine can cost less than using a traditional\nhosting provider, as App Engine standard environment provides a free tier.\n\nSites hosted on App Engine are hosted on the\n\u003cvar translate=\"no\"\u003e\u003ca href=\"#appengine-urls\" style=\"border-bottom: 1px dotted #999\" class=\"devsite-dialog-button\" data-modal-dialog-id=\"regional_url\" track-type=\"progressiveHelp\" track-name=\"modalHelp\" track-metadata-goal=\"regionalURL\"\u003eREGION_ID\u003c/a\u003e\u003c/var\u003e`.r.appspot.com`\nsubdomain, such as `[my-project-id].uc.r.appspot.com`. After you deploy your\nsite, you can map your own domain name to your App Engine hosted website.\n\nBefore you begin\n----------------\n\nBefore you can host your website on App Engine:\n\n1. Create a new Google Cloud console project or retrieve the project ID of\n an existing project to use:\n\n [Go to the Projects page](https://console.cloud.google.com/project)\n | **Tip:** You can retrieve a list of your existing project IDs with the [gcloud command line tool](#before_you_begin).\n2. Install and then initialize the Google Cloud CLI:\n\n [Download the SDK](/sdk/docs/install)\n\n### Listing your Google Cloud console project IDs\n\nFrom the command line, run: \n\n gcloud projects list\n\nOK\n\nCreating a website to host on Google App Engine\n-----------------------------------------------\n\n### Basic structure for the project\n\nThis guide uses the following structure for the project:\n\n- `app.yaml`: Configure the settings of your App Engine application.\n- `www/`: Directory to store all of your static files, such as HTML, CSS, images, and JavaScript.\n - `css/`: Directory to store stylesheets.\n - `style.css`: Basic stylesheet that formats the look and feel of your site.\n - `images/`: Optional directory to store images.\n - `index.html`: An HTML file that displays content for your website.\n - `js/`: Optional directory to store JavaScript files.\n - Other asset directories.\n\n### Creating the `app.yaml` file\n\nThe `app.yaml` file is a configuration file that tells App Engine how to\nmap URLs to your static files. In the following steps, you will add handlers\nthat will load `www/index.html` when someone visits your website, and all static\nfiles will be stored in and called from the `www` directory.\n\nCreate the `app.yaml` file in your application's root directory:\n\n1. Create a directory that has the same name as your project ID. You can find your project ID in the [Console](https://console.cloud.google.com/).\n2. In directory that you just created, create a file named `app.yaml`.\n3. Edit the `app.yaml` file and add the handlers element based on your website\n requirements. For example, `app.yaml` file for Python\n runtime may be created as follows:\n\n runtime: python39\n\n handlers:\n - url: /\n static_files: www/index.html\n upload: www/index.html\n\n - url: /(.*)\n static_files: www/\\1\n upload: www/(.*)\n\nMore reference information about the `app.yaml` file can be found in the\n[`app.yaml` reference documentation](/appengine/docs/standard/reference/app-yaml).\n\n### Creating the `index.html` file\n\nCreate an HTML file that will be served when someone navigates to the root page\nof your website. Store this file in your `www` directory. \n\n \u003chtml\u003e\n \u003chead\u003e\n \u003ctitle\u003eHello, world!\u003c/title\u003e\n \u003clink rel=\"stylesheet\" type=\"text/css\" href=\"/css/style.css\"\u003e\n \u003c/head\u003e\n \u003cbody\u003e\n \u003ch1\u003eHello, world!\u003c/h1\u003e\n \u003cp\u003e\n This is a simple static HTML file that will be served from Google App\n Engine.\n \u003c/p\u003e\n \u003c/body\u003e\n \u003c/html\u003e\n\nDeploying your application to App Engine\n----------------------------------------\n\nWhen you deploy your application files, your website will be uploaded to App\nEngine. To deploy your app, run the following command from within the root\ndirectory of your application where the `app.yaml` file is located: \n\n gcloud app deploy\n\nOptional flags:\n\n- Include the `--project` flag to specify an alternate Google Cloud console project ID to what you initialized as the default in the gcloud CLI. Example: `--project [YOUR_PROJECT_ID]`\n- Include the `-v` flag to specify a version ID, otherwise one is generated for you. Example: `-v [YOUR_VERSION_ID]`\n\nTo learn more about deploying your app from the command line, see\n[Deploying your application](/appengine/docs/standard/testing-and-deploying-your-app#deploying_your_application).\n\nViewing your application\n------------------------\n\nTo launch your browser and view the app at\n`https://`\u003cvar translate=\"no\"\u003ePROJECT_ID\u003c/var\u003e`.`\u003cvar translate=\"no\"\u003e\u003ca href=\"#appengine-urls\" style=\"border-bottom: 1px dotted #999\" class=\"devsite-dialog-button\" data-modal-dialog-id=\"regional_url\" track-type=\"progressiveHelp\" track-name=\"modalHelp\" track-metadata-goal=\"regionalURL\"\u003eREGION_ID\u003c/a\u003e\u003c/var\u003e`.r.appspot.com`, run the\nfollowing command: \n\n gcloud app browse\n\nWhat's next\n-----------\n\n[Serve your App Engine hosted website from a custom domain](/appengine/docs/standard/mapping-custom-domains)."]]