Joseph Edmonds

Running Node with Docker

by Joseph Edmonds

by Joseph Edmonds

I recently decided to set up my local system without node installed and instead user Docker so that I can very easily flip versions and don’t have any complications about incompatabilies etc.

To install Docker, I follow the normal Fedora instructions and I also set up the rootless mode, so that containers run as me rather than root.

Then once Docker is installed, I add this to my bashrc file and then basic node commands run inside a container.


# Docker Node stuff
DOCKER_NODE_VER=${DOCKER_NODE_VER:-16}
docker-node-version() {
case "$1" in
-s|--set)
if [ "$2" ]; then
DOCKER_NODE_VER="$2"
echo
echo "docker-node will now use node:$2 image!"
fi
return 0
esac
echo $DOCKER_NODE_VER
}
docker-node-image() {
echo -n "node:`docker-node-version`"
}
docker-node-run() {
set -x
local dp
# [ "$1" = "bash" ] && dp="-it"
dp="$dp -it --init --rm"
dp="$dp -p 8080:8080"
dp="$dp -v "$PWD":/usr/src/app"
dp="$dp -w /usr/src/app"
docker run $dp $(docker-node-image) "$@"
set +x
}
node() { docker-node-run "$@"; }
npm() { docker-node-run npm "$@"; }
npx() { docker-node-run npx "$@"; }
yarn() { docker-node-run yarn "$@"; }



This then means that any call to node, npm, npx or yarn will actually run in a container. I can easily change the node version by either directly overriding the DOCKER_NODE_VER variable, or calling the docker-node-version function.

Note – I didn’t create this from scratch, the original is here:
https://github.com/paulojeronimo/docker-node-shell-functions

Facebook
Twitter
LinkedIn
About Joseph Edmonds

About Joseph Edmonds

Personal musings, tech tips, trivia and other things that might be interesting.

Get in touch today

Send me a message concerning your idea, problem, or question – and I’ll personally respond as soon as possible.

Connect with me on LinkedIn.