pm2 Advanced, production process manager for Node.js

Sommai Krangpanich
Jul 20, 2017 · 1 min read

pm2 เป็นเครื่องมือสำหรับจัดการ process เพื่อให้โปรแกรมที่เราพัฒนาขึ้นมาด้วย node.js สามารถใช้ประสิทธิภาพจาก server ได้เต็มประสิทธิภาพเพราะปัญหาอย่างนึงของ node.js ก็คือเป็น single thread นั่นหมายความว่าถึงแม้เราจะมีหลาย cpu หลาย thread เราก็ไม่สามารถใช้ได้ครบ

เริ่มต้นติดตั้ง

npm install pm2 -gในกรณีที่เป็น linux / osx ติดตั้งแล้ว error อาจจะติดเรื่อง permission ให้ใช้คำสั่งนี้แทนsudo npm install pm2 -g

รันโปรแกรม

command:
pm2 start file_name.js
ex:
pm2 start app.js

คำสั่งพื้นฐาน

pm2 start file_name.js //รันโปรแกรม
pm2 list //แสดงรายการทั้งหมด
pm2 reload [app_id / name / all] //load program ใหม่
pm2 update //update code ใหม่ทั้งหมด
pm2 stop [app_id / name / all] //หยุดการทำงานของโปรแกรม
pm2 delete [app_id / name / all] //ลบ process ทิ้ง
pm2 save //เก็บข้อมูลการตั้งค่าทั้งหมดเก็บไว้ เมื่อเครื่อง restart ก็จะ start ทุก process ให้กลับมาใหม่

pm2 list มีไว้สำหรับให้ดูรายการโปรแกรมทั้งหมดที่กำลังทำงานอยู่ในตอนนี้

ตัวอย่างจากการรันคำสั่ง pm2 list

เราสามารถนำ app name, id, ไปใช้ใน คำสั่งอื่นๆ เช่น stop, reload, delete

หลังจากที่ได้ใช้ pm2 มาสักระยะนึงประมาณ 6 เดือนก็พบว่าเป็นเครื่องมาที่ช่วยให้ node.js ทำงานได้เต็มประสิทธิภาพมากขึ้น เพราะมี mode cluster ซึ่งจะช่วยให้ใช้ทุก thread ได้ อีกทั้งยังมีระบบ ecosystem ที่ช่วยให้สามารถทำเป็น config file ให้เราสามารถตั้งค่า config ได้ตาม environment

pnpsolution

Bring you a best solution.

)

Sommai Krangpanich

Written by

pnpsolution

Bring you a best solution.

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade