DEV Community

OliverOdo
OliverOdo

Posted on

Stop fighting with npm by isolating it into a container

Hello,

Let me share a small script that i'm using on my local machine to develop.

Before we start, let me share a bit more my profile: I wrote my first line of code 15 years ago and I'm not so much into following trends... Then I develop using vim, tmux and ... bash (yes still 🤪)

As you know nowadays there is new tools, new version, new framework, new system... Installing all of this into your machine has a cost.

A new way of working by isolating projects

This is why a few years ago, I made a shift to work only within Docker container... And I LOVE IT! 🚀

I made a small script to automate the flow...

As a NodeJs developer i was tired of:

  • Installing global module into my computer.
  • Using nvm to change node version.
  • Having conflict between projects.
  • Tracking all the weird files that are installed in my HOME folder
  • keep trying to save space...

Now all of those problems are gone since I don't have node installed on my computer anymore, the only way I use node is through an isolated container by using this script:


#!/bin/bash

# File located in: ~/.dotfile/scripts/docker-run.sh

port=""
while getopts "p:" arg; do
  case $arg in
    p)
      for I  in "$OPTARG"
      do
        port="-p $I $port"
      done
      ;;
  esac
done

name=${PWD##*/}

docker run --name ${name} -v $(pwd):$(pwd) --workdir $(pwd) ${port} -it node:14 bash
Enter fullscreen mode Exit fullscreen mode

and adding this into my ~/.bash_alias:

drun="sh ~/.dotfile/scripts/docker-run.sh"
Enter fullscreen mode Exit fullscreen mode

Then when i run the alias command in a project folder:

drun -p 8080:8080
Enter fullscreen mode Exit fullscreen mode

It will:

  • Create a fresh container with the name of the current folder
  • Map the 8080 port of my local machine into the 8080 port of the container.
  • Mount the current folder into the container.
  • Enter in the container.

From there, I can still edit the file from my local machine, but run any node command from the container

Example:

asciicast

Conclusion

If you are still reading until here, I think you understand the potential of this. It can be use for any use case.
I also use this tips a lot, to try different programing language without installing them.

Let's break the dependency with our machine as much as possible 😇.

I forgot: Take a look at RestQA

See Ya!


More about Me:

Top comments (0)