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.
sudo apt install nginx -ysudo service nginx startNow, 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.
sudo apt updatesudo apt install git -yUpdate 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.
curl https://get.volta.sh | bashSince 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.
sudo apt install certbot python3-certbot-nginx -yThe 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.
sudo certbot --nginx -d example.comFinally, set up automatic updates.
sudo certbot renew --dry-runRedirect 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.
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.targetsystemctl command list
| command | role |
|---|---|
sudo systemctl daemon-reload | Reload systemd configuration |
sudo systemctl enable node | Automatically start node when the OS starts |
sudo systemctl disable node | Disable automatic startup at OS startup |
sudo systemctl start node | start node now |
sudo systemctl stop node | stop node now |
sudo systemctl restart node | restart node |
sudo systemctl reload node | Change settings and reload process |
sudo systemctl status node | Check current state of node |
sudo systemctl list-units --type=service | Display list of running services |
sudo systemctl list-unit-files --type=service | View all services list |
sudo systemctl is-active node | Check if node is running |
sudo systemctl is-enabled node | Check node autostart settings |
sudo systemctl kill node | Kill node process |
sudo journalctl -u node --no-pager | Check node logs |
There is a command like the one above, so register and start the service.
sudo systemctl daemon-reloadsudo systemctl enable nodesudo systemctl start node