Are you trying to install Bcrypt in Docker?
This guide is for you.
The bcrypt library on NPM makes it really easy to hash and compare passwords in Node.
Bcrypt is the de facto way to hash and store passwords.
Here at Ibmi Media, as part of our Server Management Services, we regularly help our Customers to perform related Docker queries.
In this context, we shall look into how to install Bcrypt in docker and how to resolve the related errors.
The Bcrypt package to encrypt passwords comes with a minor challenge. While we install, it needs to comply with the operating system (OS) architecture using node-gyp, python 2.x.
On occurrences of any code change to the application, the docker image will need a rebuild to check those changes.
This will add time for every change to check, creating a slow feedback loop.
In order to solve this, we can use docker named volumes, which will link application files on our host to the docker container.
1. Initially, we run the below command on our Dockerfile:
RUN apk add –no-cache make gcc g++ python && \
npm install && \
npm rebuild bcrypt –build-from-source && \
apk del make gcc g++ python
This will install all the prerequisites for Bcrypt, then install node_modules, and then compile Bcrypt.
2. Afterward, it will remove the prerequisites to keep the docker image small as possible.
The challenge is during the development, while we work on a different OS to the Docker Container.
For instance, consider we work on Windows.
However, the docker image built is Linux.
This will cause an error when running the app because Bcrypt dependency complies against the host (Windows):
Error: /app/node_modules/bcrypt/lib/binding/bcrypt_lib.node: invalid ELF header
To resolve this issue, , we need to set up a docker-compose.yml file with a volumes field that can create a named volume to link our host files to the container.
When the host has a different OS, Bcrypt node_module will cause the error.
So, we need a way to exclude the node_modules on the host machine from being linked to the container.
For that, we need to use an anonymous volume.
An example snippet of the docker-compose file is given below:
– ./your-host-app:/usr/src/app # named volume
– /usr/src/app/node_modules # anonymous volume for node_modules only
Anonymous volumes reference the directory in the container.
On the other hand, docker handles where to store the files.
The mount is outside of our project.
This keeps the node_modules intact.
While docker-compose up, will create anonymous volume for new containers, docker-compose down does not remove them.
However, the flag -v can remove them.
If we only want to remove anonymous volumes, we can stop the containers and run docker-compose rm -vf.