Use Docker to create a node development environment (2023)

Instead of building and running a node application locally, this tutorial uses the Debian Linux operating system on which the official Docker node images are based. They create a Portable Node development environment that solves this"But it runs on my machine"A problem that constantly plagues developers as containers are built predictably from running Docker images on each platform.

In this tutorial, you will work in two areas:

  • local operating system: Using a CLI application such as Terminal or PowerShell, use a local installation of Docker to build images and run them as containers.

  • container operating system: Docker commands access the base operating system of a running container. In this context, you use a container shell to issue commands to create and run a node application.

The container operating system runs in isolation from the local operating system. Files created inside the container are not accessible locally. Servers running inside the container cannot service requests from a local web browser.This is not ideal for local development.🇧🇷 To overcome these limitations, connect these two systems as follows:

  • Mount a local folder on the container's file system: Using this mount point as your container's working directory keeps all files created in the container's location and makes the container aware of any local changes made to project files.

  • Allow the host to interact with the container network: Mapping a local port to a container port redirects all HTTP requests from the Docker local port to the container port.

To see this Docker-based Node development strategy in action, create a simple Node Express web server. Let's start!

Downloading the Node installation

To say a simple "Hello world!" Node app, the typical tutorial asks:

  • Download and Install Node
  • Download and install hilo
  • To use different versions of Node, uninstall and install Nodenvm
  • Install NPM packages globally

Use Docker to create a node development environment (1)

Each operating system has its own quirks that make previous installations non-standard. However, access to the node ecosystem can be standardized using Docker images.The only installation requirement for this tutorial is Docker.🇧🇷 If you need to install Docker, select your operating systemthis docker installation documentand follow the steps indicated.

Similar to how NPM works, Docker gives us access to a large Docker image registry calledDocker Hub🇧🇷 You can get and run different versions of Node as Docker Hub images. You can run these images as local processes that do not overlap or conflict with each other. You can simultaneously create a cross-platform project that depends on Node 8 with NPM and another that depends on Node 11 with Yarn.

Creating the base of the project.

First create one somewhere on your systemthat-stevedoreFile. This is the project directory.

To have a Node Express server under thethat-stevedoreproject directory, create aserver.jsfile, complete it as follows and save it:

// server.jsuntilexpress= demand("express");untilApplication= express();until PORTA =process.environment.PORTA || 8080;Application.to receive("/", (required,resolution) => {resolution.to send(`<h1>Docker + Nodo</h1> <span>A match in the cloud</span>`);});Application.I'm listening(PORTA, () => {console.Protocol(`The server is listening on the port.psPORTA}...`);});

A node project requires aPackage.jsonfile and anode_modulesmapsAssuming Node is not installed on your systemuse Docker to create these files following a structured workflow.

(Video) Dockerize your Development Environment

Access to the container operating system

You can access the container operating system using one of the following methods:

  • Using a single but long Docker run command.
  • Using a Dockerfile in combination with a docker run short command.
  • Using a Dockerfile in combination with Docker Compose.

with a singledocker runningdomain

Run the following command:

docker running--rm-es--us by name-dockers \-v$PCD:/I'm getting married/Application-W/I'm getting married/Inscription \-mi"PORTA=3000" -pag8080:3000\-you are:More recent/container/He tried

let's break itdocker runningThe command to understand how to access the container shell will help you:

docker run --rm -it

docker runningcreates a new container instance. That--rmbanderaautomatically stops and removes the container as soon as it leaves. the agreed-UEmi-trunning flagsinteractive processes as a shell🇧🇷 That one-UEholds STDIN (standard input) open while-tflag makes the process pretend to be a text terminal and pass signals.

think about it--rmas "out of sight, out of mind".

Without this-esTeam, you won't see anything on the screen.

Use Docker to create a node development environment (2)

docker running--rm-es--us by name-stevedore

That--Namebanderaassigns a descriptive name to the container for easy identification in records and tables. For example when runningPS docker.

docker running--rm-es--us by name-dockers \-v$PCD:/I'm getting married/Application-W/I'm getting married/Application

That-vbanderamount a local folder to a parent folder with this mapping as an argument:

<HOST MAPS RELATIVE LARGO>:<CONTAINER MAPS ABSOLUTE LARGO>

An environment variable can print the current working directory when the command is executed:psPCDsin Mac y LinuxpsCDin Windows That-Wbanderasets the mount point to the container's working directory.

docker running--rm-es--us by name-dockers \-v$PCD:/I'm getting married/Application-W/I'm getting married/Inscription \-mi"PORTA=3000" -pag8080:3000

That-mibanderasets an environment variablePORTAWorth3000🇧🇷 That one-pagbanderamap a local port8080to a container port3000adapt to environment variablePORTAconsumed internallyserver.js:

until PORTA =process.environment.PORTA || 8080;
docker running--rm-es--us by name-dockers \-v$PCD:/I'm getting married/Application-W/I'm getting married/Inscription \-mi"PORTA=3000" -pag8080:3000\-you are:More recent/container/He tried

For security reasons and to avoid file permission issues, the-Udsbanderaset non-root userthatavailable in the node image as a user running the container processes. After setting the flags, the image to run is specified:that:More recent🇧🇷 The last argument is a command to execute inside the container once it is executed./container/He triedcall the shell of the container.

If the image does not exist locally, there are issues with DockerDrag the dockerin the background to download itDocker Hub.

Once the command runs, you'll see the container shell prompt:

(Video) Live Demo of Docker Dev Environments

That@<CONTAINER ID>:/home/app$

Before proceeding to the next method, exit the container terminal by typingsalidaand pressure<LOG IN>.

wearing aDockerfile

Thatdocker runningThe command in the previous section consists of the image build time and container runtime elements and flags:

docker running--rm-es--us by name-dockers \-v$PCD:/I'm getting married/Application-W/I'm getting married/Inscription \-mi"PORTA=3000" -pag8080:3000\-you are:More recent/container/He tried

Anything related to image build time can be set as a custom imageDockerfileas follows:

  • VONspecifies the base image of the container:that:More recent
  • WORKEDare defined-W
  • OF THE USERare defined-Uds
  • ENVare defined-mi
  • ENTRY POINTindicates for execution/container/He triedonce the container is running

On this basis under thethat-stevedoreproject directory, create a file calledDockerfile, fill it like this and save:

VONthat:More recentWORKED/start/applicationOF THE USERthatENVPORTA 3000EXPOSE3000ENTRY POINT/bin/bash

EXPOSE 3000documents the port to expose at runtime. However, you must still include the container runtime stamps that define the container name, port mapping, and volume mount.docker running.

The custom image set on itDockerfileshould be built withDocker-Buildbefore it can run. In your local terminal, run:

Docker-Build-that's-stevedore.

Docker-Buildprovide your image with a display namethat-stevedoreUse of-tbandera🇧🇷 This is different from the container name. Run to verify that the image was createddockable images.

With the image created, run this shorter command to run the server:

docker run --rm -it --name nodo-docker\-v$PWD:/start/app -p8080:3000\Nodo-Docker

The container shell prompts have the following format:

That@<CONTAINER I COULD>:/I'm getting married/app$

Before proceeding to the next method, exit the container terminal once more by enteringsalidaand pressure<LOG IN>.

Using docker composition

for linux,Docker Compose is installed separately.

Based onDockerfileand the shortestdocker runningYou can use the command from the previous section to create a Docker Compose YAML file to define your Node development environment as a service:

Dockerfile:

VONthat:More recentWORKED/start/applicationOF THE USERthatENVPORTA 3000EXPOSE3000ENTRY POINT/bin/bash

domain

(Video) Docker Talks Live! Setting up your local development environment with Node.js

docker run --rm -it --name nodo-docker\-v$PWD:/start/app -p8080:3000\Nodo-Docker

The only elements that can still be abstracteddocker runningThe commands are container name, volume mount, and port mapping.

Underthat-stevedoreproject directory, create a file calledstevedore-to compose.yml, fill it with the following content and save it:

performance: "3"services: nod_dev_env: build up:.container name:that-stevedoredoors: -8080:3000 volumes: -./:/start/application
  • nod_dev_envgives the service a name to easily identify it
  • build upgives way toDockerfile
  • container nameprovide a friendly name for the container
  • doorsconfigure port mapping from host to container
  • volumessets the mount point of a local folder to a parent folder

Run the following command to start and run this service:

stevedore-to compose

hochcreates its own images and containers separate from those created bydocker runningmiDocker-Buildpreviously used commands. How to verify this execution:

dockable image# Look at the image named <project-folder>_nod_dev_envstevedorePD-a# Look at the container named <project-folder>_nod_dev_env_<number>

hochcreated an image and a container, but did not see the container's shell prompt. What happened?hochstarts the defined full-service compositionstevedore-to compose.yml🇧🇷 However, it does not provide interactive results; Instead, only static service records are displayed. For interactive results, usestevedore-ride barrelrun in placenod_dev_envindividually.

First, to clean up the created images and containers.hoch, run the following command in your local terminal:

docker-compose down

Then run the following command to run the service:

docker-compose ejecutar --rm --service-ports nod_dev_env

Thatcorrecommand acts asdocker running-es🇧🇷 However, no container port is assigned and exposed to the host. To use the port mapping configured in the docker-compose file, use the--Service-doorsFlag. The container shell prompt appears again in the following format:

That@<CONTAINER I COULD>:/I'm getting married/app$

If for some reason the ports specified in the Docker Compose file are already in use, you can use the--to post, (-pag) to manually specify a different port assignment. For example, the following command assigns the host port4000to the container port3000:

docker-compose run --rm -p4000:3000 nod_dev_env

Installation of dependencies and execution of the server.

If you don't have an active container shell, use one of the methods in the previous section to access it.

In the container shell, initialize the node project and install the dependencies by issuing the following commands (optional, usenpm):

fioinitialize -yfio addexpressfio add-D nodemonio

Look at thisPackage.jsonminode_modulesare now available at your locationthat-stevedoreproject directory.

Nakedsimplifies your development workflow by automatically restarting the server when you make changes to the source code. set upNaked, UpdatePackage.jsonas follows:

{ // Other properties... "hyphens": { "start": "server nodemon.js" }}

Run in container shellstart the threadto run the node server.

(Video) How to Setup a Docker Based Linux Development Environment

To test the server, visithttp://host location: 8080/in your local browser. Docker intelligently redirects host port request8080to the container port3000.

To test the content of the local file and the server connection, openserver.jsUpdate the response locally as follows and save your changes:

// server.js// Package definitions and constants...Application.to receive("/", (required,resolution) => {resolution.to send(`<h1>Hello from node running on Docker</h1>`);});// The server is listening...

Refresh the browser window and note the new response.

Modify and extend the project.

Assuming Node is not installed on your local system, you can use the local terminal to change the project structure and file content, but you cannot run Node-related commands, such asadd wires🇧🇷 Also, since the server runs inside the container, it cannot make requests from the server to the internal port of the container.3000.

In case you want to interact with the server inside the container or change the node layout, you have to run commands in the running container usingexecutive couplerand the ID of the running container. you don't usedocker runningsince that command would create a new isolated container.

Getting the id of the running container is easy.

  • If you already have a container shell open, the container ID will be at the shell prompt:

That@<CONTAINER I COULD>:/I'm getting married/app$

  • You can also get the container id programmatically withPS dockerto filter containers by name and return theCONTAINER I COULDfrom a game:
stevedorePD-qf"nome=node-docker"

That-FThe flag filters the containers byName=that-stevedoreDisease. That-q(--calm) restricts the output to display only the mail id, which makes theCONTAINER I COULDVonthat-stevedorenoexecutive couplerDomain.

Once you get the container id you can useexecutive couplerfor:

  • Open a new instance of the running container shell:
stevedoreexecutive-espsstevedorePD-qf"nome=node-docker")/bin/bash
  • Make a server request through the internal port3000:
stevedoreexecutive-espsstevedorePD-qf"nome=node-docker") shirred rufflehost location: 3000
  • Install or remove dependencies:
stevedoreexecutive-espsstevedorePD-qf"nome=node-docker") fio addbody analyzer

If you have another container shell active, you can run it without any problemshirred rufflemiadd wiresthere instead.

Recapitulate... and discover little lies

You learned how to create an isolated Node development environment through different levels of complexity: creating a singledocker runningcommand with aDockerfileto build and run a custom image and use Docker Compose to run a container as a Docker service.

Each level requires more file configuration but a shorter command to run the container. This is a valid compromise, as encapsulating the configuration in files makes the environment portable and easier to maintain. You also learned how to interact with a running container to extend your project.

You may still need to install Node locally for IDEs to provide syntax support, or you can use a CLI editor likepushinside the container.

Use Docker to create a node development environment (3)

However, you can benefit from this isolated development environment. Restricting execution of the project's setup, installation, and runtime steps within the container allows you to standardize these steps across your team, since all commands would be executed on the same version of Linux. Also, all cache and hidden files created by Node tools stay in the container and do not overload the local system. Oh and you have one toofiofree!

(Video) development environment in docker in 5 minutes

JetBrainsNombreprovides the ability to use Docker images as a remote interpreter for Node and Python when running and debugging applications. In the future, we may completely prohibit the download and installation of these tools directly on our systems. Stay tuned to see what the industry has to offer to make our developer environments standardized and portable.

About Auth0

Okta Auth0 takes a modern approach to customer identity, enabling organizations to provide secure access to any application for any user. Auth0 is a highly customizable platform that is as simple as development teams want and as flexible as they need. Auth0 protects billions of login transactions every month, providing convenience, privacy, and security so customers can focus on innovation. For more information visithttps://auth0.com.

FAQs

Can you use Docker as a development environment? ›

Docker is a great way to provide consistent development environments. It will allow us to run each of our services and UI in a container. We'll also set up things so that we can develop locally and start our dependencies with one docker command. The first thing we want to do is dockerize each of our applications.

How to create a dev environment with Docker? ›

To launch a dev environment:
  1. From Dev Environments in Docker Dashboard, select Create. ...
  2. Select Get Started.
  3. Optional: Provide a name for you dev environment.
  4. Select Existing Git repo as the source and then paste your Git repository link into the field provided.
  5. Choose your IDE. ...
  6. Select Continue.

How to use Docker image for development? ›

Learning objectives
  1. Install the Visual Studio Code Dev Containers extension.
  2. Load and connect to a project in a Docker container.
  3. Access ports in the container from your local machine.
  4. Customize settings while working with your container.
  5. Add software to the container environment.

Is Docker becoming obsolete? ›

But now with modern containerisation tools and container orchestration services in place (such as Kubernetes and OpenShift ) docker provides too much then it's needed to get things running. In this article we will see briefly what is containerisation, how does docker came into place and why it's becoming obsolete.

Is Docker good for deployment? ›

Docker enables faster software delivery cycles

Docker containers make it easy to put new versions of software, with new business features, into production quickly—and to quickly roll back to a previous version if you need to. They also make it easier to implement strategies like blue/green deployments.

Is it good to run database in Docker? ›

In Conclusion

Docker is great for running databases in a development environment! You can even use it for databases of small, non-critical projects which run on a single server. Just make sure to have regular backups (as you should in any case), and you'll be fine.

Can I use Docker Desktop for local development? ›

Docker simplifies configuration under Docker Desktop, taking care of port mappings, file system concerns, and other default settings, making it seamless to develop on your local machine.

Should you run DB in Docker? ›

However, using Docker to run a database server in a container instead of installing it directly on your local computer can easily resolve this issue. In general, Docker is not designed for stateful services, so it is not highly recommended to run a database in a docker container in a production environment.

Does Docker do development? ›

Develop with Docker
  • Learn how to build an image using a Dockerfile.
  • Use multi-stage builds to keep your images lean.
  • Manage application data using volumes and bind mounts.
  • Scale your app with Kubernetes.
  • Scale your app as a Swarm service.
  • General application development best practices.

Do developers use Docker? ›

For millions of developers today, Docker is the de facto standard to build and share containerized apps – from desktop, to the cloud. We are building on our unique connected experience from code to cloud for developers and developer teams.

Is Docker a development or production? ›

Docker Compose is an excellent tool for optimizing the process of creating development, testing, staging, and production environments.

Is Docker used in development or production? ›

- Docker integrates perfectly with the concept of DevOps, especially in the area of versioning: development and production are carried out in the same container. Put simply, if the application works on the Dev side, it will also work on the Ops side.

Videos

1. Learn Docker - DevOps with Node.js & Express
(freeCodeCamp.org)
2. How to setup development environment using docker.
(Anirudha Gupta)
3. How To Build a Node.JS Application with Docker | Getting Started with Docker Using Node.js
(ProgrammingKnowledge)
4. Developer Environments in Docker
(Docker)
5. Using Python and Docker to create a novel and scalable development environment solution
(PyCon Canada)
6. Docker-izing a NodeJS ExpressJS API - Tutorial
(TutorialEdge)
Top Articles
Latest Posts
Article information

Author: Delena Feil

Last Updated: 05/18/2023

Views: 6129

Rating: 4.4 / 5 (45 voted)

Reviews: 84% of readers found this page helpful

Author information

Name: Delena Feil

Birthday: 1998-08-29

Address: 747 Lubowitz Run, Sidmouth, HI 90646-5543

Phone: +99513241752844

Job: Design Supervisor

Hobby: Digital arts, Lacemaking, Air sports, Running, Scouting, Shooting, Puzzles

Introduction: My name is Delena Feil, I am a clean, splendid, calm, fancy, jolly, bright, faithful person who loves writing and wants to share my knowledge and understanding with you.