dockergoogle-cloud-platformgoogle-compute-engine

Can I map port(s) from a container to its host on GCE using `gcloud create-with-container`?


I am trying to spin up a dockerized web app on my GCE instance. I want to be able to access my app from the external ip provided by GCE without SSH-ing into my instance to map the ports. gcloud compute instances create-with-container instance-1 --container-image=image:latest creates a instance with a container of my image but it does not seem to allow me to map the ports. Is there some way to do this without ssh-ing into my instance?

Do I need to do all of this from the startup script ie.

Appreciate you all taking the time to help me out here. Thanks in advance.


Solution

  • You are absolutely correct. The gcloud compute instances create-with-container command doesn’t directly support mapping container ports to the host VM’s port on GCE . However there is a simple and more secure approach to achieve what you need.

    Here how to expose your containerized web app on GCE without ssh or manual port mapping in the startup script .

    Modify your dockerfile to instruct the container to expose the port your web app listens to.

    Expose 8080  # Replace 8080 with the actual port your app uses
    
    CMD  [your app entrypoint ] #Replace with your app startup script  command
    

    This expose instruction informs the container engine that contains listens on a specific port.

    Instead of manually mapping ports, leverage a load balancer to distribute traffic to your container instances. Refer to Abdelilah OUASSINI’s Medium doc on Sample Load balancing solution with Docker and Nginx for more details.

    GCE offers two options:

    1. Network load balancer is ideal for Layer 4 (TCP/UDP) traffic balancing and scales automatically.

    2. HTTP(S) Load balancer is designed for Layer 7 (HTTP/HTTPS) traffic balancing features like path based routing and ssl termination.Choose the load balancer that best suits your app needs.

    Now use the gcloud command -line tool to create the chosen load balancer in your GCE project. The specific command will vary depending on the load balancer type you select.

    After that you need to create a backend service which is a group of backend instances (your container instances) that the load balancer distributes traffic to configure the backend service to point to your container instances using managed instance groups or directly referencing vms .

    Load Balancer can perform health checks to ensure your container instances are healthy and receiving traffic. This helps maintain high availability by removing unhealthy instances from the pool.

    By following the above steps, leveraging a load balancer, you can expose your containerized web app publicly on GCE without needing SSH access or manual port mapping on the host VM.