02. Bootstrap Node.js on EC2
While I worked at Cognizant during the publishing of this post / video, the views expressed here are my own and may not reflect those of my employer. Only publicly available material is used to put together the content of this article and video. The website and the Youtube videos are NOT monetized.
EC2 User data is probably the best way to bootstrap your instance. While AWS Documentation provides a great way to install Node.js on EC2 server once it is up, instructions provided in there are a little tricky to put together in a user data script / command. Primary reason being that the instructions don’t use a standard package manager (yum / apt-get).
Here is the simplest way to achieve that with a shell script, you can specify it in the User data
Here’s a screenshot
install_node.sh
#!/bin/bash
USER=ec2-user # For Ubuntu AMI mention ubuntu etc.
NODE_VERSION=node # installs latest, for specific mention version number e.g. 8.9.4
su - $USER -c "#!/bin/bash; cd ~ ;curl -o- https://raw.githubusercontent.com/creationix/nvm/v0.32.0/install.sh > install.sh;chmod +x install.sh;./install.sh; cd .nvm ; chmod +x nvm.sh ;. ./nvm.sh ; nvm install $NODE_VERSION"
Copy the above content into a file on your computer and provide that for user data (Configure Instance -> Advanced Details -> User data, select As file and provide this file)
The script installs the latest version of node but you can also specify a particular version, for example to install version 8.9.4, assign version number like this
NODE_VERSION=8.9.4 # installs latest, for specific mention version number e.g. 8.9.4
In case of AMIs other than Amazon Linux please update the USER for example in case of an Ubuntu AMI, assign following
USER=ubuntu # For Ubuntu AMI mention ubuntu etc.
Script Actions
- Download the NVM (node version manager) install script
- Changes permissions to make it executable
- Installs NVM
- Loads NVM paths to profile
- Installs Node.js
Installation Verification
Once the EC2 instance is provisioned and running, login and run following command
node -v
Installation logs can be found in /var/log/cloud-init-output.log
# /var/log/cloud-init-output.log
Installing Node.js for ec2-user version (node)
% Total % Received % Xferd Average Speed Time Time Time Current
Dload Upload Total Spent Left Speed
^M 0 0 0 0 0 0 0 0 --:--:-- --:--:-- --:--:-- 0^M100 10007 100 10007 0 0 43334 0 --:--:-- --:--:-- --:--:-- 43508
=> Downloading nvm as script to '/home/ec2-user/.nvm'
=> Appending source string to /home/ec2-user/.bashrc
=> Close and reopen your terminal to start using nvm or run the following to use it now:
export NVM_DIR="/home/ec2-user/.nvm"
[ -s "$NVM_DIR/nvm.sh" ] && . "$NVM_DIR/nvm.sh" # This loads nvm
######################################################################## 100.0%
Computing checksum with sha256sum
Checksums matched!
Now using node v11.8.0 (npm v6.5.0)
Thank you for reading
-Nikhil