# Start Node.js on Google Cloud

日本語版: 日本語で読む

Table of Contents

When I was looking for a cloud service to run Node.js as cheaply as possible, I found Google I learned that Cloud could be used for free under certain conditions, so I started the server and ran Node.js.

Google Cloud free tier

The free tier of Computing Engine is as follows.

  • e2-micro One non-preemptible VM instance per month in one of the following US regions:
  • Oregon: us-west1
  • Iowa: us-central1
  • South Carolina: us-east1
  • 30 GB/month standard persistent disk
  • 1GB monthly outbound data transfer from North America to all regions (excluding China and Australia)

More details here.

computing engine

In the first place, what a computing engine is is officially written as follows.

Compute Engine is a computing and hosting service that lets you create and run virtual machines on Google’s infrastructure.

It’s the same as ES2 in AWS, which everyone loves.

Launch an instance with Google Cloud’s compute engine

Log in to Google Cloud and select Compute Engine from the side menu.

Select a VM instance and create an instance.

Then, select the one that meets the conditions of the free tier mentioned above.

Next, under the Networking tab, click on Firewall.

  • Allow HTTP traffic
  • Allow HTTPS traffic

Check the box.

I created it without checking this, so I had a hard time connecting.

The instance launch is now complete.

~~It’s been 2 days since I started using this method, but I haven’t received a bill, so it seems like there will be no problem with using the free tier. ~~

I feel like I’m being charged something, so I need to check it out.

Make it accessible from a browser

Clicking SSH on the VM instance will launch a console in your browser, where you can execute commands.

Install nginx

Install and start nginx.

Terminal window
sudo apt install nginx -y
sudo service nginx start

Now, when you visit the external IP of your instance, you will see a screen like the one below.

Welcome to nginx!
If you see this page, the nginx web server is successfully installed and working. Further configuration is required.
For online documentation and support please refer to nginx.org.
Commercial support is available at nginx.com.
Thank you for using nginx.

Launch the node app

Install Git

I want to run the Node.js app on Git, so first install Git.

Terminal window
sudo apt update
sudo apt install git -y

Update Advanced Package Tool and install Git.

Next, I want to install Node.js, but since I am using Volta as a package tool, I will install Volta first.

Terminal window
curl https://get.volta.sh | bash

Since Volta automatically installs Node.js listed in package.json, the installation of Node.js is completed.

Finally, Clone the Node.js app on Git.

Start Node.js

Next, configure Nginx as a reverse proxy to forward HTTP requests to your Node.js app (port 3000).

Change /etc/nginx/sites-available/default to the following.

server {
# サーバーがリッスンするポートを指定(HTTPの標準ポート80)
listen 80;
# サーバーのホスト名やIPアドレスを指定
# ここでは「外部IP」へのリクエストを処理する
server_name 外部IP;
# ルートパス("/")へのリクエストを処理
location / {
# リクエストをリバースプロキシし、ポート3000で動作するローカルのNode.jsアプリに転送
proxy_pass http://localhost:3000; # Node.js アプリが動作しているポート
# クライアントの "Host" ヘッダーをそのままバックエンド(Node.js)に渡す
proxy_set_header Host $host;
# クライアントの実際のIPアドレスを "X-Real-IP" ヘッダーとしてバックエンドに渡す
proxy_set_header X-Real-IP $remote_addr;
# クライアントの元のIPアドレスを "X-Forwarded-For" ヘッダーとしてバックエンドに渡す
# プロキシを経由した場合でも、すべての経由したIPアドレスがリストされる
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
# クライアントがHTTPかHTTPSのどちらでアクセスしたかをバックエンドに伝える
proxy_set_header X-Forwarded-Proto $scheme;
}
}

I wasn’t able to catch up with my understanding, so I asked them to comment out on Chat GPT.

I’m not sure, but it seems that when / is accessed, it is forwarded to http://localhost:3000.

So, I restarted Nginx, applied the settings, started Node.js, and the app was displayed.

Get your own domain and a free SSL certificate from Let’s Encrypt

Skip acquiring and setting up your own domain.

Terminal window
sudo apt install certbot python3-certbot-nginx -y

The above will install the following plugins.

certbot → A tool to obtain and renew Let’s Encrypt’s free SSL certificate. python3-certbot-nginx → Plugin that allows Certbot to integrate with Nginx.

Next, get a free SSL certificate from Let’s Encrypt.

Terminal window
sudo certbot --nginx -d example.com

Finally, set up automatic updates.

Terminal window
sudo certbot renew --dry-run

Redirect from HTTP to HTTPS in Nginx settings

with sudo nano /etc/nginx/sites-available/default

server {
listen 80; # HTTPリクエストを受け付けるポート
server_name {domain}; # この設定が適用されるドメイン名
# HTTPアクセスをHTTPSにリダイレクト
return 301 https://$host$request_uri;
}
server {
listen 443 ssl; # HTTPSリクエストを受け付けるポート
server_name {domain}; # この設定が適用されるドメイン名
# Let's Encryptで取得したSSL証明書のパスを指定
ssl_certificate /etc/letsencrypt/live/{domain}/fullchain.pem;
ssl_certificate_key /etc/letsencrypt/live/{domain}/privkey.pem;
# サポートするTLSのバージョンを指定(TLS1.2およびTLS1.3のみを許可)
ssl_protocols TLSv1.2 TLSv1.3;
# 安全な暗号スイートを指定(脆弱なアルゴリズムを排除)
ssl_ciphers HIGH:!aNULL:!MD5;
# ドキュメントルート(公開ディレクトリ)の設定
root /var/www/html;
# デフォルトのインデックスファイルを指定
index index.html index.htm index.nginx-debian.html;
# ルートパス(/)へのリクエストを処理
location / {
# リクエストされたURIが存在する場合はそのファイルを提供
# ディレクトリとして存在する場合はそのディレクトリを開く
# どちらにも該当しない場合は404エラーを返す
try_files $uri $uri/ =404;
}
# /search-items へのリクエストをNode.jsアプリ(ポート3000)に転送
location /search-items {
proxy_pass http://127.0.0.1:3000; # ローカルのNode.jsアプリへリクエストを転送
# クライアントのホスト情報を転送
proxy_set_header Host $host;
# クライアントのIPアドレスを転送
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
# クライアントのプロトコル情報(http/https)を転送
proxy_set_header X-Forwarded-Proto $scheme;
}
}

Modify like this and restart with sudo systemctl restart nginx.

I didn’t fully understand this either, so I asked them to comment it out.

I want to start Node.js all the time

I created a Mastodon bot using PM2. When I made the application persistent using PM2, I was told that systemd was better, so I tried using systemd this time.

First, create a service file.

Terminal window
sudo nano /etc/systemd/system/node.service
[Unit]
# サービスの説明(任意)
Description=My Node.js App
# このサービスはネットワークが起動した後に起動する
After=network.target
[Service]
# Node.js の実行ファイル(Volta 経由)を使用してアプリを起動
ExecStart=/home/{username}/.volta/bin/node /home/{path}/app.js
# 作業ディレクトリを指定(相対パス解決のため)
WorkingDirectory=/home/{path}
# アプリが異常終了した場合でも自動で再起動
Restart=always
# 実行するユーザーを指定(セキュリティ上、root ではなく専用ユーザーを使う)
User={username}
# 環境変数 NODE_ENV を production に設定
Environment=NODE_ENV=production
# 環境変数を .env ファイルから読み込む
EnvironmentFile=/home/{path}/.env
# 標準出力を syslog に記録
StandardOutput=syslog
# 標準エラー出力も syslog に記録
StandardError=syslog
# syslog に記録する際の識別子(ログ確認時に `node-app` で検索可能)
SyslogIdentifier=node-app
[Install]
# `systemctl enable node-app` で OS 起動時に自動起動させるためのターゲット
WantedBy=multi-user.target

systemctl command list

commandrole
sudo systemctl daemon-reloadReload systemd configuration
sudo systemctl enable nodeAutomatically start node when the OS starts
sudo systemctl disable nodeDisable automatic startup at OS startup
sudo systemctl start nodestart node now
sudo systemctl stop nodestop node now
sudo systemctl restart noderestart node
sudo systemctl reload nodeChange settings and reload process
sudo systemctl status nodeCheck current state of node
sudo systemctl list-units --type=serviceDisplay list of running services
sudo systemctl list-unit-files --type=serviceView all services list
sudo systemctl is-active nodeCheck if node is running
sudo systemctl is-enabled nodeCheck node autostart settings
sudo systemctl kill nodeKill node process
sudo journalctl -u node --no-pagerCheck node logs

There is a command like the one above, so register and start the service.

sudo systemctl daemon-reload
sudo systemctl enable node
sudo systemctl start node

More Posts
My avatar

Thanks for reading my blog post! Feel free to check out my other posts or contact me via the social links in the footer.


Comments