Google App Engine 502 (Bad Gateway) with NodeJS
I have a full web application using NodeJS, MongoDB (Mongoose as the driver) and ExpressJS.
The project works perfectly on my local machine. Today I decided to move everything to production. I'm using Google App Engine to host my application, and Compose (formally MongoHQ) to host my database.
App Engine servers my application perfectly, although my API does not seem to work. My API is served from example.com/api
, and each request (GET
, POST
, DELETE
and PUT
) all returns a 502 (Bad Gateway) error.
I tried running my application on my local machine while connected to my remote MongoDB database and that worked perfectly fine. So it must be a problem with App Engine or NodeJS, not with MongoDB.
I have tried checking all error logs within Google Cloud, although there are no errors.
Why is App Engine/NodeJS serving my application's static content perfectly fine, although not allowing any requests to my API?
Solution 1:
just make sure that your server listens on 8080 port https://cloud.google.com/appengine/docs/flexible/custom-runtimes/build#listen_to_port_8080
Solution 2:
502 Bad Gateway is usually an error on the Nginx side. Unfortunately those logs are not surfaced to Cloud Logging, yet.
A lot of times the problem is that your HTTP packets are too big for the buffers or something similar. The way you can see the nginx log is something like this:
- Use just 1 VM. This isn't strictly necessary, but a lot of times it makes it easier to debug your application if you know that your requests on the one machine. You can accomplish this by adding this to your app.yaml:
manual_scaling:
instances: 1
then re-deploy
Switch the VM from "Google owned" to self-managed. This can be done in the Cloud Console. Go to Compute Engine, instances, click on the instance name that matches the App Engine version, and you should see an option to switch it to self-managed.
gcloud compute ssh <instance name>
to SSH to the machinedocker ps
to see your running containers. Look for the container named nginx and grab its id.Once you have a container ID, you should be able to
docker exec -it <container id> -- cat /var/log/nginx/error.log
. You might want tols
that whole log directory.
You will likely see an error there which will be a bigger hint as to what's going wrong.
I know this is way more complicated than it should be :-\ If you have any problems with the steps above, leave a comment. If you do find an error and you're not sure what to do with it, also leave a comment.