Mantenha tudo organizado com as coleções
Salve e categorize o conteúdo com base nas suas preferências.
Saiba como definir limites para a memória usada pelas instâncias de contêiner no
Knative serving.
Noções básicas sobre o uso da memória
As instâncias de contêiner do Knative serving que excedem o limite de
memória permitido são encerradas.
Os itens a seguir afetam a memória disponível da instância do contêiner:
Abrir o executável do aplicativo (já que o executável precisa ser carregado na
memória).
Alocar memória no processo do aplicativo.
Gravar arquivos no sistema.
O tamanho da imagem de contêiner implantada não afeta a memória
disponível.
Quantidade máxima de memória
A quantidade máxima de memória que é possível configurar é limitada pela configuração
do cluster do GKE.
Como otimizar a memória
É possível determinar o requisito de pico de memória para um serviço usando:
(Memória permanente) + (Memória por solicitação) * (Simultaneidade do serviço)
Portanto:
se você aumentar a simultaneidade do serviço, também precisará aumentar o limite de memória para contabilizar o pico de uso;
se você diminuir a simultaneidade do serviço, considere reduzir o limite de memória para economizar nos custos de uso dela.
Qualquer mudança na configuração leva à criação de uma nova revisão. As próximas revisões também recebem automaticamente essa configuração, a menos que você faça atualizações explícitas para alterá-la.
Você pode definir limites de memória usando o Console do Cloud, a CLI do Google Cloud ou um arquivo YAML ao implantar um novo
serviço ou atualizar um serviço existente e
implantar uma revisão:
Console
Acesse o Knative serving no console do Google Cloud:
Clique em Criar serviço se estiver configurando um
novo serviço em que fará uma implantação. Se você estiver configurando um
serviço atual, clique nele e em
Editar e implantar uma nova revisão.
Em Configurações avançadas, clique em Contêiner.
Selecione o tamanho de memória que você quer na lista suspensa
Memória alocada.
Clique em Avançar para acessar a próxima seção.
Na seção Configurar como este serviço é acionado,
selecione qual conectividade você quer usar para invocar o serviço.
Clique em Criar para implantar a imagem no Knative serving e aguarde
até que a implantação seja concluída.
Linha de comando
Para os serviços existentes, atualize o limite de memória usando o
comando gcloud run services update com o
parâmetro
--memory:
gcloudrunservicesupdateSERVICE--memorySIZE
Substitua:
SERVICE pelo nome do serviço;
SIZE pelo tamanho de memória desejado. O formato para o tamanho é um número de ponto fixo ou flutuante seguido
por uma unidade: G, M ou K, correspondente a gigabyte, megabyte ou kilobyte,
respectivamente. Também é possível usar a potência de dois equivalentes: Gi, Mi, Ki,
correspondente a gibibyte, mebibyte ou kibibyte, respectivamente.
Para novos serviços, defina o limite da memória executando o comando
gcloud run deploy
com o parâmetro
--memory:
IMAGE_URL por uma referência à imagem de contêiner. Por
exemplo, gcr.io/cloudrun/hello;
SIZE pelo tamanho de memória desejado. O formato para o tamanho é um número de ponto fixo ou flutuante seguido
por uma unidade: G, M ou K, correspondente a gigabyte, megabyte ou kilobyte,
respectivamente. Também é possível usar a potência de dois equivalentes: Gi, Mi, Ki,
correspondente a gibibyte, mebibyte ou kibibyte, respectivamente.
YAML
Faça o download da configuração de um serviço existente para um
arquivo YAML com o comando gcloud run services describe usando a
sinalização --format=export.
Em seguida, modifique o arquivo YAML e implante
essas alterações com o comando gcloud run services replace.
Modifique apenas os atributos especificados.
Faça o download da configuração do serviço em um arquivo chamado
service.yaml no espaço de trabalho local:
Substitua SIZE pelo tamanho de memória desejado.
O formato é um número de ponto fixo ou flutuante seguido por uma unidade:
G, M, ou K correspondente a gigabyte, megabyte ou kilobyte,
respectivamente. Ou use a potência de dois equivalentes: Gi, Mi, Ki
correspondente a gibibyte, mebibyte ou kibibyte respectivamente.
Substitua o serviço pela nova configuração usando o seguinte comando:
[[["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-22 UTC."],[],[],null,["# Configuring memory limits\n\nLearn how to set limits for the memory used by your container instances in\nKnative serving.\n\nUnderstanding memory usage\n--------------------------\n\nKnative serving container instances that exceed their allowed\nmemory limit are terminated.\n\nThe following count towards the available memory of your container instance:\n\n- Running the application executable (as the executable must be loaded to memory)\n- Allocating memory in your application process\n- Writing files to the filesystem\n\nThe size of the deployed container image does not count towards the available\nmemory.\n\nMaximum amount of memory\n------------------------\n\nThe maximum amount of memory you can configure is limited by the configuration\nof your GKE cluster.\n\nOptimizing memory\n-----------------\n\nYou can determine the peak memory requirement for a service using the\nfollowing: **(Standing Memory) + (Memory per Request) \\* (Service Concurrency)**\n\nAccordingly,\n\n- If you raise the concurrency of your service, you should also\n increase the memory limit to account for peak usage.\n\n- If you lower the concurrency of your service, consider reducing the memory\n limit to save on memory usage costs.\n\nFor more guidance on minimizing per request memory usage read\n[Development Tips on Global Variables](/kubernetes-engine/enterprise/knative-serving/docs/tips/general#using_global_variables).\n\nSetting and updating memory limits\n----------------------------------\n\nAny configuration change leads to the\ncreation of a new revision. Subsequent revisions will also automatically get\nthis configuration setting unless you make explicit updates to change it.\n\nYou can set memory limits using the Google Cloud console,\nthe Google Cloud CLI, or a YAML file when you deploy a new\n[service](/kubernetes-engine/enterprise/knative-serving/docs/deploying#service) or update an existing service and\ndeploy a [revision](/kubernetes-engine/enterprise/knative-serving/docs/deploying#revision): \n\n### Console\n\n\n1. Go to Knative serving in the Google Cloud console:\n\n [Go to Knative serving](https://console.cloud.google.com/kubernetes/run)\n2. Click **Create Service** if you are configuring a\n new service you are deploying to. If you are configuring an\n existing service, click on the service, then click\n **Edit \\& Deploy New Revision**.\n\n3. Under *Advanced settings* , click **Container**.\n\n4. Select the desired memory size from the\n **Memory allocated** dropdown list.\n\n5. Click **Next** to continue to the next section.\n\n6. In the **Configure how this service is triggered** section,\n select which connectivity you would like to use to invoke the service.\n\n7. Click **Create** to deploy the image to Knative serving and wait\n for the deployment to finish.\n\n### Command line\n\n- For existing services, update the memory limit by running the\n `gcloud run services update` command with the\n [`--memory`](/sdk/gcloud/reference/run/services/update#--memory)\n parameter:\n\n ```bash\n gcloud run services update SERVICE --memory SIZE\n ```\n\n Replace:\n - \u003cvar translate=\"no\"\u003eSERVICE\u003c/var\u003e with the name of your service.\n - \u003cvar translate=\"no\"\u003eSIZE\u003c/var\u003e with the desired memory size. The format for size is a fixed or floating point number followed by a unit: `G`, `M`, or `K` corresponding to gigabyte, megabyte, or kilobyte, respectively, or use the power-of-two equivalents: `Gi`, `Mi`, `Ki` corresponding to gibibyte, mebibyte or kibibyte respectively.\n- For new services, set the memory limit by running the\n `gcloud run deploy` command with the\n [`--memory`](/sdk/gcloud/reference/run/deploy#--memory)\n parameter:\n\n ```bash\n gcloud run deploy SERVICE --image=IMAGE_URL --memory SIZE\n ```\n\n Replace:\n - \u003cvar translate=\"no\"\u003eSERVICE\u003c/var\u003e with the name of your service.\n - \u003cvar translate=\"no\"\u003eIMAGE_URL\u003c/var\u003e with a reference to the container image, for example, `gcr.io/cloudrun/hello`.\n - \u003cvar translate=\"no\"\u003eSIZE\u003c/var\u003e with the desired memory size. The format for size is a fixed or floating point number followed by a unit: `G`, `M`, or `K` corresponding to gigabyte, megabyte, or kilobyte, respectively, or use the power-of-two equivalents: `Gi`, `Mi`, `Ki` corresponding to gibibyte, mebibyte or kibibyte respectively.\n\n### YAML\n\n| **Caution:** Deploying configuration changes using YAML files replaces the configuration of your existing services. Since a YAML file completely overwrites all configurations, you should avoid using multiple methods to modify your services. For example, do not use YAML files in conjunction with the Google Cloud console or `gcloud` commands.\n\nYou can download the configuration of an existing service into a\nYAML file with the `gcloud run services describe` command by using the\n[`--format=export`](/sdk/gcloud/reference/run/services/describe) flag.\nYou can then modify that YAML file and deploy\nthose changes with the `gcloud run services replace` command.\nYou must ensure that you modify only the specified attributes.\n\n1. Download the configuration of your service into a file named\n `service.yaml` on local workspace:\n\n ```bash\n gcloud run services describe SERVICE --format export \u003e service.yaml\n ```\n\n Replace \u003cvar translate=\"no\"\u003eSERVICE\u003c/var\u003e with the name of your\n Knative serving service.\n2. In your local file, update the `memory` attribute:\n\n ```yaml\n apiVersion: serving.knative.dev/v1\n kind: Service\n metadata:\n name: SERVICE_NAME\n spec:\n template:\n spec:\n containers:\n -- image: IMAGE_URL\n resources:\n limits:\n memory: SIZE\n ```\n\n Replace \u003cvar translate=\"no\"\u003eSIZE\u003c/var\u003e with the desired memory size.\n The format is a fixed or floating point number followed by a unit:\n `G`, `M`, or `K` corresponding to gigabyte, megabyte, or kilobyte,\n respectively, or use the power-of-two equivalents: `Gi`, `Mi`, `Ki`\n corresponding to gibibyte, mebibyte or kibibyte respectively.\n3. Replace the service with its new configuration using the following command:\n\n ```bash\n gcloud run services replace service.yaml\n ```"]]