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 Node
nvm
- Install NPM packages globally
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-stevedore
File. This is the project directory.
To have a Node Express server under thethat-stevedore
project directory, create aserver.js
file, 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.json
file and anode_modules
mapsAssuming Node is not installed on your systemuse Docker to create these files following a structured workflow.
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 running
domain
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 running
The command to understand how to access the container shell will help you:
docker run --rm -it
docker running
creates a new container instance. That--rm
banderaautomatically stops and removes the container as soon as it leaves. the agreed-UE
mi-t
running flagsinteractive processes as a shell🇧🇷 That one-UE
holds STDIN (standard input) open while-t
flag makes the process pretend to be a text terminal and pass signals.
think about it
--rm
as "out of sight, out of mind".Without this
-es
Team, you won't see anything on the screen.
docker running--rm-es--us by name-stevedore
That--Name
banderaassigns 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-v
banderamount 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:psPCD
sin Mac y LinuxpsCD
in Windows That-W
banderasets 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-mi
banderasets an environment variablePORTA
Worth3000
🇧🇷 That one-pag
banderamap a local port8080
to a container port3000
adapt to environment variablePORTA
consumed 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-Uds
banderaset non-root userthat
available 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 tried
call the shell of the container.
If the image does not exist locally, there are issues with Docker
Drag the docker
in the background to download itDocker Hub.
Once the command runs, you'll see the container shell prompt:
That@<CONTAINER ID>:/home/app$
Before proceeding to the next method, exit the container terminal by typingsalida
and pressure<LOG IN>
.
wearing aDockerfile
Thatdocker running
The 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 imageDockerfile
as follows:
VON
specifies the base image of the container:that:More recent
WORKED
are defined-W
OF THE USER
are defined-Uds
ENV
are defined-mi
ENTRY POINT
indicates for execution/container/He tried
once the container is running
On this basis under thethat-stevedore
project directory, create a file calledDockerfile
, fill it like this and save:
VONthat:More recentWORKED/start/applicationOF THE USERthatENVPORTA 3000EXPOSE3000ENTRY POINT/bin/bash
EXPOSE 3000
documents 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 itDockerfile
should be built withDocker-Build
before it can run. In your local terminal, run:
Docker-Build-that's-stevedore.
Docker-Build
provide your image with a display namethat-stevedore
Use of-t
bandera🇧🇷 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 enteringsalida
and pressure<LOG IN>
.
Using docker composition
for linux,Docker Compose is installed separately.
Based onDockerfile
and the shortestdocker running
You 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
docker run --rm -it --name nodo-docker\-v$PWD:/start/app -p8080:3000\Nodo-Docker
The only elements that can still be abstracteddocker running
The commands are container name, volume mount, and port mapping.
Underthat-stevedore
project 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_env
gives the service a name to easily identify itbuild up
gives way toDockerfile
container name
provide a friendly name for the containerdoors
configure port mapping from host to containervolumes
sets the mount point of a local folder to a parent folder
Run the following command to start and run this service:
stevedore-to compose
hoch
creates its own images and containers separate from those created bydocker running
miDocker-Build
previously 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>
hoch
created an image and a container, but did not see the container's shell prompt. What happened?hoch
starts 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 barrel
run in placenod_dev_env
individually.
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
Thatcorre
command 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-doors
Flag. 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 port4000
to 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, use
npm
):
fioinitialize -yfio addexpressfio add-D nodemonio
Look at thisPackage.json
minode_modules
are now available at your locationthat-stevedore
project directory.
Naked
simplifies your development workflow by automatically restarting the server when you make changes to the source code. set upNaked
, UpdatePackage.json
as follows:
{ // Other properties... "hyphens": { "start": "server nodemon.js" }}
Run in container shellstart the thread
to run the node server.
To test the server, visithttp://host location: 8080/
in your local browser. Docker intelligently redirects host port request8080
to the container port3000
.
To test the content of the local file and the server connection, openserver.js
Update 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 coupler
and the ID of the running container. you don't usedocker running
since 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 with
PS docker
to filter containers by name and return theCONTAINER I COULD
from a game:
stevedorePD-qf"nome=node-docker"
That
-F
The flag filters the containers byName=that-stevedore
Disease. That-q
(--calm
) restricts the output to display only the mail id, which makes theCONTAINER I COULD
Vonthat-stevedore
noexecutive coupler
Domain.
Once you get the container id you can useexecutive coupler
for:
- Open a new instance of the running container shell:
stevedoreexecutive-espsstevedorePD-qf"nome=node-docker")/bin/bash
- Make a server request through the internal port
3000
:
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 problem
shirred ruffle
miadd wires
there instead.
Recapitulate... and discover little lies
You learned how to create an isolated Node development environment through different levels of complexity: creating a singledocker running
command with aDockerfile
to 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 likepush
inside the container.
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 toofio
free!
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? ›- From Dev Environments in Docker Dashboard, select Create. ...
- Select Get Started.
- Optional: Provide a name for you dev environment.
- Select Existing Git repo as the source and then paste your Git repository link into the field provided.
- Choose your IDE. ...
- Select Continue.
- Install the Visual Studio Code Dev Containers extension.
- Load and connect to a project in a Docker container.
- Access ports in the container from your local machine.
- Customize settings while working with your container.
- Add software to the container environment.
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.
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.
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? ›- 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.
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.