This tutorial is the second part of the series on raspberry pi. In this part we will focus on the installation of MongoDB and Node.js that will run at startup. MongoDB is a popular NOSQL database that is often used with Node.js which is a JavaScript runtime mainly used to build server-side applications.
MongoDB
Let’s get started with the MongoDB installation which is pretty simple:
$ sudo apt-get update
$ sudo apt-get upgrade
$ sudo apt-get install mongodb-server
And to start it as a service when the raspberry pi starts just have to enter this command:
$ sudo service mongod start
The binaries are stored in the /usr/bin/
folder while the datas are in the /var/lib/mongodb/
folder. You can check everything is ok by using the mongo shell:
$ mongo
Node.js
Now we are going to install the Node.js server on our raspberry pi and put it as a service. Firstly download the latest version:
$ wget https://nodejs.org/dist/latest-v5.x/node-v5.11.0-linux-armv7l.tar.gz
You can download another version here but be careful to take the linux-armv7l distribution.
Once the archive downloaded, extract the package, move it in the /opt/node
folder and create the symbolic links:
$ tar -xvzf node-v5.11.0-linux-armv7l.tar.gz
$ sudo mv node-v5.11.0-linux-armv7l /opt/node
$ sudo mkdir /opt/bin
$ sudo ln -s /opt/node/bin/* /opt/bin/
To finish the installation, let’s add the binaries in the PATH
:
$ sudo nano /etc/profile
PATH="/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/opt/bin"
Press CTRL+O
then CTRL+X
to save the file. Voilà! The installation is done, check that everything is ok by taping these commands:
$ npm --version
3.7.3
$ node -v
v5.9.1
Run your web server as a service
Now that you have node and npm installed on your raspberry pi 2 you can work with your web server. Imagine you have a really simple on the /home/pi/dev/node
folder named app.js
with this code:
const http = require('http');
const hostname = '0.0.0.0';
const port = 3000;
const server = http.createServer((req, res) => {
res.statusCode = 200;
res.setHeader('Content-Type', 'text/plain');
res.end('Hello World\n');
});
server.listen(port, hostname, () => {
console.log(`Server running at http://${hostname}:${port}/`);
});
Here is just a hello world to illustrate the tutorial that you can run using this command node /home/pi/dev/node/app.js
To run it as a service, we are firstly going to create a file in the /etc/init.d/
folder to have our own service. Let’s create a node
file:
$ sudo nano /etc/init.d/node
And put the following content:
#!/bin/sh
# /etc/init.d/node
if [ true != "$INIT_D_SCRIPT_SOURCED" ] ; then
set "$0" "$@"; INIT_D_SCRIPT_SOURCED=true . /lib/init/init-d-script
fi
### BEGIN INIT INFO
# Provides: node
# Required-Start: $all
# Required-Stop: $all
# Default-Start: 2 3 4 5
# Default-Stop: 0 1 6
# Short-Description: Starts the DAEMON_PATH/DAEMONOPTS server
# Description: Starts the DAEMON_PATH/DAEMONOPTS server
### END INIT INFO
export PATH=$PATH:/opt/node/bin
DAEMON_PATH="/home/pi/dev/node"
DAEMON=node
DAEMONOPTS="app.js"
NAME=node
DESC="myprogram"
PIDFILE=/var/run/$NAME.pid
SCRIPTNAME=/etc/init.d/$NAME
case "$1" in
start)
printf "%-50s" "Starting $NAME..."
cd $DAEMON_PATH
PID=`$DAEMON $DAEMONOPTS > /dev/null 2>&1 & echo $!`
#echo "Saving PID" $PID " to " $PIDFILE
if [ -z $PID ]; then
printf "%s\n" "Fail"
else
echo $PID > $PIDFILE
printf "%s\n" "Ok"
fi
;;
status)
printf "%-50s" "Checking $NAME..."
if [ -f $PIDFILE ]; then
PID=`cat $PIDFILE`
if [ -z "`ps axf | grep ${PID} | grep -v grep`" ]; then
printf "%s\n" "Process dead but pidfile exists"
else
echo "Running"
fi
else
printf "%s\n" "Service not running"
fi
;;
stop)
printf "%-50s" "Stopping $NAME"
PID=`cat $PIDFILE`
cd $DAEMON_PATH
if [ -f $PIDFILE ]; then
kill -HUP $PID
printf "%s\n" "Ok"
rm -f $PIDFILE
else
printf "%s\n" "pidfile not found"
fi
;;
restart)
$0 stop
$0 start
;;
*)
echo "Usage: $0 {status|start|stop|restart}"
exit 1
esac
exit 0
This file simply describes how to service should start or stop. Then you can start your custom service using this command:
$ sudo service node start
You just have to restart your raspberry pi 2 and everything should be ok. If not try this command line sudo update-rc.d node defaults
Conclusion
The installation of MongoDB and Node.js is pretty simple. If you have some troubles or questions don’t hesitate to leave a comment.
cant get mongo to work!!! on latest raspbian with a Pi2
Got mongo working with these instructions http://andyfelong.com/2016/01/mongodb-3-0-9-binaries-for-raspberry-pi-2-jessie/
Hello guys, been using this tutorial to install NodeJS on my Raspberry Pi 3 and all work except the “service” part. I put the app.js file exactly as said and place the node file in /etc/init.d/ but as i try to run it by using sudo service node start i got the following :
Failed to start node.service: Unit node.service failed to load: No such file or directory.
Can you explain me where i went wrong ?
Ok so find the mistake. There is a double quote that is not actually correct right after “app.js”. I removed it and put a correct double quote, then “systemctl daemon-reload” and it works
Thank you!
Thanks!
I don’t understand. I don’t see where I should remove double quote. Is it possible to help me please ?
There’s a typo in the instructions:
sudo apt-get mongodb-server
should be:
sudo apt-get install mongodb-server
Thank you for your help!
When starting Mongodb the command should be:-
sudo service mongodb start NOT sudoservice mongod start as above!!
Thank you! I couldn’t figure out why it didn’t work.
Thank you!
Hello, if for one reason the web server crashes, it will restar automatically using this configuration? or I have to do something else? Thanks
to run mongod
sudo /etc/init.d/mongodb start
Thanks
sudo service mongod start
doesn’t work for me, I keep getting:
Failed to start mongod.service: Unit mongod.service failed to load: No such file or directory.
Any idea?
Setup: Raspberry 3 with a fresh+unaltered install of Raspbian 4.4 (download today).
same here ! did you find why ?
Just in case someone has this problem, it’s because you need to do: `sudo service mongodb start` notice “mongodb”. Otherwise you’ll be prompt this error
Getting following error:
pi@raspberrypi ~ $ sudo apt-get install mongodb-server
Reading package lists… Done
Building dependency tree
Reading state information… Done
Package mongodb-server is not available, but is referred to by another package.
This may mean that the package is missing, has been obsoleted, or
is only available from another source
E: Package ‘mongodb-server’ has no installation candidate
Thanks for the post, for me this worked fine on my Pi 3, but maybe it’s because I tried earlier in June when there’s wasn’t an Arm7 release for the Pi. AT that time I followed Andy Felong’s setup recommendations which may have paved the way for this success.
I had compiled a Mongo 3 release, but the binary was 160 times the size of this Mongo 2 release.
My advice to others would be to review any setup prerequisites in the Mongo install docs first. It’s likely that in time these issues will be baked into the package.
I’m encountering the same issue. Any suggestion?
Hello
I’m a complete beginner to MEAN stack and would like to work with Raspberry Pi with MEAN stack For IOT project. What’s the most simplest project i can do which satisfies the title “Using the MEAN Stack to Implement a RESTful Service for an Internet of Things Application”.
Kindly Reply
Thanks
Thank you for a great tutorial! I just want to say that you missed a character when you start the MongoDB service. It should be: sudo service mongodb start
Where it states ‘sudo service mongod start’ it should be:
sudo service mongodb start
Anyone else who is getting a 404 on the node link use the following to get Node v8.1.4
wget https://nodejs.org/dist/latest/node-v8.1.4-linux-armv7l.tar.gz
Then just follow same procedure, obviously replacing any instances of ‘node-v5.11…’ in any commands with the correct file/folder name of the one you have just downloaded.
Worked for me, thanks!
Thanks, this works for me but its always advisable to check https://nodejs.org/dist/latest/ …to know the latest version and substitute the name in the above command. E.g the latest version as at now is :v10.1.0
Hey very helpful, but heads up: `sudo service mongod start` should be `sudo service mongodb start`
Hi,
command: npm –version —is not working, it returns this error: -bash: npm: command not found.
command: node -v … worked returning value: v4.8.2
Please what could have gone wrong? the npm seemed not to have been installed. Your advice will be really appreciated. Thanks in advance.
Now that we have the 64 bit r-pi 3B+, we should be able to install a newer version of mongodb. I’m looking forward to seeing a tutorial for the installation of a full MEAN stack on the pi 🙂
And how to run these versions with Angular CLI anyway? Angular CLI only accepts Node.js version 8.9. If I start MongoDB, then I receive an error messange that I have to install MongoDB 2.6.
This has nothing to do with the double quotes.
To solve this you have to make the node file executable with the following commands.
sudo chmod 755 node
sudo update-rc.d node defaults
Then it works