Nesta página, você aprende a ativar uma porta Secure Sockets Layer (SSL) ao implantar o Extensible Service Proxy V2
(ESPv2) com o Google Kubernetes Engine, Kubernetes ou
Compute Engine. Talvez você queira ativar uma porta SSL para o serviço do Endpoints implantado em alguns casos de uso.
Antes de começar, leia os tutoriais sobre o tipo de serviço e ambiente escolhidos e saiba como implantar
o ESPv2 sem SSL.
Como configurar chaves e certificados SSL
Para configurar a porta SSL para exibir solicitações HTTPS, siga as etapas abaixo:
Verifique se o nome do arquivo de chave SSL é server.key e se o arquivo do certificado se chama server.crt. Para o teste, você pode gerar server.key e server.crt assinados automaticamente
usando o OpenSSL com o seguinte comando:
Especifique CN e subjectAltName no certificado do servidor. O valor desses atributos
precisa corresponder ao DNS ou ao IP usado pelos clientes para chamar o serviço. Caso contrário, o
handshake SSL falhará.
Como ativar o SSL para ESPv2 no Kubernetes
Para ativar a porta SSL para ESPv2 no Kubernetes, siga as seguintes etapas:
Crie um secret do Kubernetes com o certificado e a chave SSL:
Observação: a amostra de configuração exibe as linhas que precisam ser editadas. Para implantar o arquivo no Cloud Endpoints é necessário o arquivo de configuração completo.
Inicie o ESPv2 conforme descrito em
Como especificar opções de inicialização para o ESPv2,
mas certifique-se de adicionar a sinalização de inicialização --ssl_server_cert_path para especificar o caminho para os arquivos de certificado ativados.
Inicie o serviço com o arquivo de configuração atualizado do Kubernetes usando kubectl.
kubectl apply -f echo-ssl.yaml
Use o comando OpenSSL a seguir para gerar o certificado
raiz do cliente:
Se o cliente estiver usando curl, o arquivo client.pem poderá ser usado na
sinalização --caroot. Para o gRPC, o client.pem é usado como o arquivo de certificado raiz
da credencial SSL do canal gRPC.
Atualizar certificados SSL
É importante atualizar o certificado SSL periodicamente.
Para atualizar seus certificados SSL, é necessário executar as seguintes etapas:
Crie novos certificados, conforme descrito na etapa 1 acima.
Ative os novos certificados nos secrets do Kubernetes, conforme descrito na etapa 3 acima.
Atualize a implantação do ESPv2 do Kubernetes, conforme descrito na etapa 5 acima.
Gere o arquivo de certificado raiz do cliente novamente, conforme descrito na etapa 6 acima.
Como ativar o SSL para o ESPv2 no Compute Engine
Para ativar o SSL no Compute Engine, primeiro copie os arquivos server.key e server.crt para a
pasta /etc/nginx/ssl da instância do Compute Engine usando as seguintes etapas:
Execute o seguinte comando e substitua INSTANCE_NAME
pelo nome da instância do Compute Engine:
gcloud compute scp server.* INSTANCE-NAME
Conecte-se à instância usando ssh.
gcloud compute ssh INSTANCE-NAME
Na caixa "VM da instância", crie o diretório e copie os arquivos:
Em comparação com o comando docker run não SSL, a versão SSL do
comando cria uma configuração diferente. Por exemplo, o comando SSL:
monta a pasta com arquivos de chave e CRT no contêiner usando
--volume;
usa --ssl_server_cert_path=/etc/esp/ssl para informar ao ESPv2 para encontrar
os arquivos de certificado do servidor server.key e server.crt na pasta /etc/esp/ssl;
altera a sinalização de mapeamento de porta --publish. As solicitações recebidas para a porta HTTPS 443 são mapeadas para a porta 9000 do ESPv2.
Atualizar certificados SSL
É importante atualizar o certificado SSL periodicamente.
Para atualizar seus certificados SSL, é necessário executar as seguintes etapas:
Crie novos certificados e copie-os em instâncias de VM, conforme descrito na etapa 1 acima.
Copie os novos certificados para o diretório /etc/esp/ssl, conforme descrito na etapa 3 acima.
Interrompa e reinicie o contêiner do ESPv2 usando o comando sudo docker run, conforme descrito na etapa 4 acima.
Teste da porta SSL
Para facilitar o teste da porta SSL, defina as seguintes variáveis de ambiente:
Defina IP_ADDRESS como o endereço IP da instância do Compute Engine com o novo certificado SSL.
Defina ENDPOINTS_KEY como uma chave de API válida.
Com a porta SSL ativada, você pode usar HTTPS para enviar solicitações ao Extensible Service Proxy. Se o certificado for assinado automaticamente, use -k para ativar a opção não segura em curl:
Como alternativa, gere o certificado no formato pem e use a opção --cacert para usar o certificado assinado automaticamente em curl, como mostrado abaixo:
[[["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-09-04 UTC."],[[["\u003cp\u003eThis document provides instructions on how to enable a Secure Sockets Layer (SSL) port for Extensible Service Proxy V2 (ESPv2) deployments on Google Kubernetes Engine, Kubernetes, or Compute Engine.\u003c/p\u003e\n"],["\u003cp\u003eTo use SSL, users must configure self-managed SSL keys and certificates, ensuring that the \u003ccode\u003eserver.key\u003c/code\u003e and \u003ccode\u003eserver.crt\u003c/code\u003e files are correctly named and contain both \u003ccode\u003eCN\u003c/code\u003e and \u003ccode\u003esubjectAltName\u003c/code\u003e matching the DNS or IP of the service.\u003c/p\u003e\n"],["\u003cp\u003eFor Kubernetes, an SSL secret must be created and mounted as a volume to the ESPv2 container, with the ESPv2 startup options updated to include the \u003ccode\u003e--ssl_server_cert_path\u003c/code\u003e flag.\u003c/p\u003e\n"],["\u003cp\u003eOn Compute Engine, the \u003ccode\u003eserver.key\u003c/code\u003e and \u003ccode\u003eserver.crt\u003c/code\u003e files need to be copied to the \u003ccode\u003e/etc/esp/ssl\u003c/code\u003e directory on the instance, and the ESPv2 Docker command must include volume mounting and the \u003ccode\u003e--ssl_server_cert_path\u003c/code\u003e flag.\u003c/p\u003e\n"],["\u003cp\u003eSSL certificates need to be updated periodically by creating new certificates, mounting them to the respective environments (Kubernetes secrets or Compute Engine directories), updating the ESPv2 deployment or container, and regenerating the client root certificate file.\u003c/p\u003e\n"]]],[],null,["# Enabling SSL for Cloud Endpoints with ESPv2\n\nOpenAPI \\| [gRPC](/endpoints/docs/grpc/enabling-ssl-espv2 \"View this page for the Cloud Endpoints gRPC docs\")\n\n\u003cbr /\u003e\n\nThis page explains how to enable a Secure Sockets Layer (SSL) port when deploying Extensible Service Proxy V2\n(ESPv2) with Google Kubernetes Engine, Kubernetes, or\nCompute Engine. You may want to enable an SSL port for your deployed Endpoints service for some use cases.\n\nBefore you begin, make sure that you have already reviewed the [tutorials](/endpoints/docs/openapi/tutorials) for your chosen service type and environment, and know how to deploy\nESPv2 without SSL.\n| **Note:** This tutorial describes how to use *self-managed SSL certificates* with ESPv2. Google-managed SSL certificates aren't currently supported by ESPv2.\n\nConfiguring your SSL keys and certificates\n------------------------------------------\n\nTo configure your SSL port to serve HTTPS requests, follow the steps below:\n\n1. Check to ensure that your SSL key file is named `server.key` and your certificate file is named `server.crt`. For testing, you can generate a self-signed `server.key` and\n `server.crt` using OpenSSL with the following command:\n\n ```\n openssl req -x509 -nodes -days 365 -newkey rsa:2048 \\\n -keyout ./server.key -out ./server.crt\n ```\n2. Specify both `CN` and `subjectAltName` in your server certificate. The value of these attributes\n should match the DNS or IP used by clients to call your service; otherwise, the\n SSL handshake will fail.\n\nEnabling SSL for ESPv2 on Kubernetes\n------------------------------------\n\nTo enable the SSL port for ESPv2 on Kubernetes:\n\n1. Create a Kubernetes secret with your SSL key and certificate:\n\n ```\n kubectl create secret generic esp-ssl \\\n --from-file=./server.crt --from-file=./server.key\n ```\n2. Edit the Kubernetes configuration files, for example, `echo-ssl.yaml`,\n as shown in the following snippet:\n\n template:\n metadata:\n labels:\n app: esp-echo\n spec:\n volumes:\n - name: esp-ssl\n secret:\n secretName: esp-ssl\n containers:\n - name: esp\n image: gcr.io/endpoints-release/endpoints-runtime:2\n args: [\n \"--listener_port\", \"9000\",\n \"--backend\", \"127.0.0.1:8081\",\n \"--service\", \"SERVICE_NAME\",\n \"--rollout_strategy\", \"managed\",\n \"--ssl_server_cert_path\", \"/etc/esp/ssl\",\n ]\n ports:\n - containerPort: 9000\n volumeMounts:\n - mountPath: /etc/esp/ssl\n name: esp-ssl\n readOnly: true\n - name: echo\n image: gcr.io/endpoints-release/echo:latest\n ports:\n - containerPort: 8081\n\n\n **Note**: The configuration sample displays the lines that need to be edited. To deploy the file to Cloud Endpoints, the complete configuration file is required.\n | **Note:** The ESPv2 container cannot bind to privileged ports, including port 443. Instead, use a Kubernetes Service resource to map 443 to a non-privileged `--listener_port`, such as `9000`.\n3. Mount the Kubernetes secrets you created as volumes, following the\n directions in the [Kubernetes volumes\n page](https://kubernetes.io/docs/concepts/storage/volumes/).\n\n4. Start up ESPv2 as described in\n [Specifying startup options for ESPv2](/endpoints/docs/openapi/specify-esp-v2-startup-options),\n but make sure you add the startup flag `--ssl_server_cert_path` to specify the path for the mounted certificate files.\n\n5. Start the service with the updated Kubernetes configuration file by using `kubectl`.\n\n \u003cbr /\u003e\n\n ```\n kubectl apply -f echo-ssl.yaml\n ```\n\n \u003cbr /\u003e\n\n | **Note:** If you already have an existing [Kubernetes\n | deployment](http://kubernetes.io/docs/user-guide/deployments/), you can [update the deployment](http://kubernetes.io/docs/user-guide/deployments/#updating-a-deployment) directly.\n6. Generate the root certificate for the client by using the following OpenSSL\n command:\n\n \u003cbr /\u003e\n\n ```\n openssl x509 -in ./server.crt -out ./client.pem -outform PEM\n \n ```\n\n \u003cbr /\u003e\n\n If the client is using `curl`, the file `client.pem` can be used in the\n `--caroot` flag. For gRPC, the `client.pem` is used as the root certificate\n file of the SSL credential for gRPC channel.\n\n### Update SSL certificates\n\nIt is important to update your SSL certificates periodically.\nTo update your SSL certificates, you must perform the following steps:\n\n- Create new certificates, as described in Step 1 above.\n- Mount the new certificates to the Kubernetes secrets, as described in Step 3 above.\n- Update the ESPv2 Kubernetes deployment, as described in Step 5 above.\n- Regenerate the client root certificate file, as described in Step 6 above.\n\nEnabling SSL for ESPv2 on Compute Engine\n----------------------------------------\n\nTo enable SSL on Compute Engine, first copy the `server.key` and `server.crt` files to\nyour Compute Engine instance's `/etc/nginx/ssl` folder, using the following steps:\n\n1. Run the following command and replace \u003cvar translate=\"no\"\u003eINSTANCE_NAME\u003c/var\u003e\n with the name of your Compute Engine instance:\n\n ```\n gcloud compute scp server.* INSTANCE-NAME\n ```\n2. Connect to the instance using `ssh`.\n\n ```\n gcloud compute ssh INSTANCE-NAME\n ```\n3. In the instance VM box, make the directory and copy in the files:\n\n sudo mkdir -p /etc/esp/ssl\n sudo cp server.* /etc/esp/ssl/\n\n4. Follow the instructions for your service type to deploy with Docker. When you\n run the ESPv2 Docker container, use this command:\n\n ```\n sudo docker run --name=esp \\\n --detach \\\n --publish=443:9000 \\\n --net=esp_net \\\n --volume=/etc/esp/ssl:/etc/esp/ssl \\\n gcr.io/endpoints-release/endpoints-runtime:2 \\\n --service=SERVICE_NAME \\\n --rollout_strategy=managed \\\n --backend=echo:8080 \\\n --ssl_server_cert_path=/etc/esp/ssl \\\n --listener_port=9000\n ```\n\n As compared to the non-SSL `docker run` command, the SSL version of the\n command creates a different configuration. For example, the SSL command:\n - Mounts the folder with the key and CRT files to the container by using `--volume`.\n - Uses `--ssl_server_cert_path=/etc/esp/ssl` to tell ESPv2 to find the server certificate files `server.key` and `server.crt` in the `/etc/esp/ssl` folder.\n - Changes the port mapping flag `--publish`. Incoming requests to HTTPS port 443 are mapped to ESPv2 port 9000.\n\n | **Note:** The ESPv2 container cannot bind to privileged ports, including port 443. Instead, use the `--publish` flag to map 443 to a non-privileged `--listener_port`, such as `9000`.\n\n### Update SSL certificates\n\nIt is important to update your SSL certificates periodically.\nTo update your SSL certificates, you must perform the following steps:\n\n- Create new certificates and copy them into VM instances, as described in Step 1 above.\n- Copy the new certificates into the `/etc/esp/ssl` directory, as described in Step 3 above.\n- Stop and restart the ESPv2 container using the `sudo docker run` command, as described in Step 4 above.\n\nTesting the SSL port\n--------------------\n\nTo make the testing the SSL port easier, set the following environment variables:\n\n1. Set \u003cvar translate=\"no\"\u003eIP_ADDRESS\u003c/var\u003e to the IP address of the Compute Engine instance with the new SSL certificate.\n\n | **Note:** The example test commands below assume that the server does not yet have a fully qualified domain name (FQDN) and that \u003cvar translate=\"no\"\u003eIP_ADDRESS\u003c/var\u003e has been used as the FQDN when generating the self-signed certificate. When the server does get an FQDN, use the FQDN to generate the certificate. Then, replace \u003cvar translate=\"no\"\u003eIP_ADDRESS\u003c/var\u003e with the FQDN in the example commands below.\n2. Set \u003cvar translate=\"no\"\u003eENDPOINTS_KEY\u003c/var\u003e to a valid [API key](https://console.cloud.google.com/apis/credentials).\n\nOnce the SSL port is enabled, you can use HTTPS to send requests to the\nExtensible Service Proxy. If your certificate is self-signed,\nuse `-k` to turn on the insecure option in `curl`: \n\n```\ncurl -k -d '{\"message\":\"hello world\"}' -H \"content-type:application/json\" \\\nhttps://IP_ADDRESS:443/echo?key=ENDPOINTS_KEY\n```\n\nAlternatively, generate the certificate in `pem` format and use the `--cacert` option to use the self-signed certificate in `curl`, as shown below: \n\n openssl x509 -in server.crt -out client.pem -outform PEM\n curl --cacert \"./client.pem\" -d '{\"message\":\"hello world\"}' -H \"content-type:application/json\" \\\n https://\u003cvar translate=\"no\"\u003eIP_ADDRESS\u003c/var\u003e:443/echo?key=\u003cvar translate=\"no\"\u003eENDPOINTS_KEY\u003c/var\u003e"]]