Tuesday, 24 July 2018

Ultra minimal docker Node.JS example

This is how to get a minimal docker image with just node and run a simple service.
Docker will automatically download the image for alpine-node if you do not already have it.
Use the run command to create and start the new container.
Use -p to publish the container port 3000 on the host at port 3000 on the IP address of the host.
Use -it to connect interactively to the TTY so you can enter and run commands

docker run -p 3000:3000 -it mhart/alpine-node

Your command line is now inside the docker container.
Edit the code of the service.
Copy and paste the sample code below and save the file.

vi service.js

Run node on the service.

node service.js

Open your web browser to the IP address of your host system using :3000 to set the request port.
You should see the hello message.
Use Ctrl+c to exit node & Ctrl+d to exit the container.

You now have a functional container that is set up to run this simple script.
Use the ls --all command to see the container you built.

docker container ls --all

Use the start command to start the container up again.
Use the container ID you found from the ls command.

docker container start <CONTAINER ID>

Check that the container is running and publishing port 3000.

docker container ls

Use the attach command to re-attach to the container.

docker container attach

Run the node command again.

node service.js




var http = require('http');

var server = http.createServer( function(req, res) {
 if (req.url === '/') {
  res.write("Hello World!");
  res.write("I have been expecting you.");
  res.end();
 }

 if (req.url === '/snarky') {
  res.write("If you code it, it will crash!");
  res.end(); 
 }

});

// Port 3000 on IPv4
server.listen(3000, "0.0.0.0");

Thursday, 12 July 2018

BASH date picker

Sometimes I need users to pick a date from within a bash shell but I need the format to be correct. This little script lets users pick a date and it will output in whatever format the script needs.

Users can use the arrow keys to move the date on the calendar and press enter to select the date.


#!/bin/bash

DONE=0
DATE=$(date +%F)
YEAR="$(echo $DATE | cut -b1-4)"
MONTH="$(echo $DATE | cut -b6-7)"
DAY="$(echo $DATE | cut -b9-10 | sed -e 's/^0/ /')"
while [ $DONE -eq 0 ]; do
 clear
 cal -h ${MONTH} ${YEAR} | GREP_COLOR='47;30' grep "$DAY" -wC6 --color=always
 read -rsn1 KEY
 [[ $KEY == $'\x1b' ]] && { 
  read -rsn1 -t 0.1 DC
  read -rsn1 -t 0.1 KP
  case $KP in
   "A") DATE=$(date +%F -d "$DATE 7 day ago");;
   "B") DATE=$(date +%F -d "$DATE 7 day");;
   "C") DATE=$(date +%F -d "$DATE 1 day");;
   "D") DATE=$(date +%F -d "$DATE 1 day ago");;
  esac
 } || { 
  DONE=1
 }
 
 YEAR="$(echo $DATE | cut -b1-4)"
 MONTH="$(echo $DATE | cut -b6-7)"
 DAY="$(echo $DATE | cut -b9-10 | sed -e 's/^0/ /')"
done
echo $DATE

# To change the output format use the date command like these examples do
# date +%d/%m/%Y -d "$DATE"
# date -d "$DATE"