JIYIK CN >

Current Location:Home > Learning > OPERATING SYSTEM > Docker >

Copy the directory from the host to the Docker image

Author:JIYIK Last Updated:2025/03/25 Views:

The Docker documentation defines Docker as an infrastructure-independent tool that helps developers develop, release, and run applications in the fastest way possible.

In addition to these benefits, DevOps developers use Docker for continuous integration, delivery, and deployment. This development approach, often referred to as CI/CD, uses containers to develop, test, and deploy changes or features to production.

The bugs in the application are fixed in the development environment. Once completed, automated testing is performed in the test environment. Finally, when all the tests pass, the image with the new changes is deployed to the production environment.

This tutorial will teach us how to copy a directory from a host to a docker image. We will do this using an express application that returns an API.


Create a quick app

Open Intellij IDEA. Select File -> New -> Project . In the window that opens, select Node.js on the left and change the project name from untitled to employee-api. Finally, click the Create button to generate a project.

To install Express in our application, open a new terminal window on Intellij IDEA by selecting View > Tool Windows > Terminal and install Express using the following command.

~/WebstormProjects/employee-api$ npm install express

After installing express, create a folder called main-app inside the folder employee-api. Then, to create our API, create a file called index.js inside the folder main-app and copy and paste the following code bar into the file.

const express = require('express')
const app = express()
const port = 3000

app.get('/', (req, res) => {
    res.json(
        [{
            name: 'Bob',
            email: "bob@gmail.com"
        },
            {
                name: 'Alice',
                email: 'alice@gmail.com'
            },
        ])
})

app.listen(port, () => {
    console.log(`Example app listening on port ${port}`)
})

In this file, we have created an express application that exposes port 3000 and any request to the path / will return an array of employees. We will use this application in all the examples presented in the following sections.


Using the ADD instruction

Create a file called Dockerfile in our base folder employee-api and copy and paste the following code into the file.

FROM node:16.17.0-alpine
WORKDIR /com/employee
ADD package*.json ./
RUN npm install
ADD main-app /com/employee/main-app
CMD node main-app/index.js

To create a custom image of an application, we usually use a file called Dockerfile, as shown in this example. The following section defines the meaning of each command used in the file. We are concerned with the ADD command on the second-to-last line.

All commands used in the previous code examples are briefly described below:

  • FROM - The first command declared in a Dockerfile, its main purpose is to declare the base image that we will use to build the image. Note that the base image is pulled from a public repository.
  • WORKDIR - sets the working directory. This will create the working directory even if we have not set it in other directives.
  • ADD - Copies a file or folder from a source to a destination. The source is usually the host machine and the destination is the container's file system.
  • RUN - Executes the provided command on top of an existing image and returns a new image containing the results of the execution. In this case, the command installs dependencies on the current image. And the resulting image is equipped with the dependencies.
  • CMD - When we start a container, this instruction provides default values ​​for the container, including the executable or entry point instruction. In this case, we used the shell form of the instruction. In addition, we provided an executable as the default for our container.

请注意, we have used the ADD instruction to copy the main-app directory from our host to the new directory created in our working directory /com/employee/main-app. To see it in action, create an image with the tag employee-api using the following command.

~/WebstormProjects/employee-api$ docker build --tag employee-api:latest.

Watch the first five instructions on the console until the build succeeds. Then, make sure you can see the instructions being executed, as shown below.

 => [1/5] FROM docker.io/library/node:16.17.0-alpine@sha256:2c405ed42fc0fd6aacbe5730042640450e5ec030bada7617beac88f742b6997b                         0.0s
 => [internal] load build context                                                                                                                    0.1s
 => => transferring context: 137B                                                                                                                    0.0s
 => CACHED [2/5] WORKDIR /com/employee                                                                                                               0.0s
 => CACHED [3/5] ADD package*.json ./                                                                                                                0.0s
 => CACHED [4/5] RUN npm install                                                                                                                     0.0s
 => CACHED [5/5] ADD main-app /com/employee/main-app  

The last instruction is executed when we run a container from our image. For example, use the following command to run a container from our image.

~/WebstormProjects/employee-api$ docker run --name employee-service -d -p 3000:3000 employee-api:latest 

This command runs a container named employee-service using our image employee-api in detached mode -d and maps port -p 3000 to port 3000 on the local host.

To verify that our application is working as expected, go to localhost:3000 http://localhost:3000/to get the employee data. Following is the JSON array returned by the request.

[
    {
    "name": "Bob",
    "email": "bob@gmail.com"
    },
    {
    "name": "Alice",
    "email": "alice@gmail.com"
    }
]

Using the COPY command

Comment the instructions in the file named Dockerfile and copy and paste the following code into the commented file.

FROM node:16.17.0-alpine
WORKDIR /com/employee
ADD package*.json ./
RUN npm install
COPY main-app /com/employee/main-app
CMD node main-app/index.js

请注意, these instructions are the same as in the previous example. The only change we made was to replace the ADD instruction in the second-to-last line with a COPY instruction.

COPY - Copies a file or folder from a source to a destination. The source is usually the host machine and the destination is the container's file system.

请注意, the COPY instruction is similar to the ADD instruction in that they achieve the same goal. To see it in action, use the commands we used in the previous example to create an image and run a container from the image.

We can either create a new image or recreate an existing image. To recreate an existing image, we need to stop the running container, remove the container, and then remove the image. Use the following commands to perform the steps separately.

~/WebstormProjects/employee-api$ docker stop employee-service 
~/WebstormProjects/employee-api$ docker rm -f employee-service 
~/WebstormProjects/employee-api$ docker rmi -f employee-api:latest 

Alternative method using ADD instruction

Comment the instructions in the file named Dockerfile and copy and paste the following code into the commented file.

FROM node:16.17.0-alpine
WORKDIR /com/employee
ADD package*.json ./
RUN npm install
ADD . .
CMD node main-app/index.js

请注意, This example is similar to the previous one, the only change we made is to replace the COPY instruction with an ADD instruction. The ADD instruction in this example uses two dots. . to specify the source and destination.

Indicates that we want to copy all the contents of the current directory to the working directory. So, for example, with this command, we can add the main-app folder and its contents to the working directory /com/employee in the image , which is much easier than the other examples.

We can use the .dockerignore file to add files and folders that we don't want to be added to the image. Then, use the commands we used in the previous examples to build the image and run the container from the image.

The output is still the same since we did not change any code in the express application.

So, we have learned how to copy a directory from the host to our image's file system. We can also copy one directory to another using the ADD and COPY instructions.

We can also use the COPY instruction with two dots COPY. .It will still produce the same effect.

For reprinting, please send an email to 1244347461@qq.com for approval. After obtaining the author's consent, kindly include the source as a link.

Article URL:

Related Articles

Docker deploys nginx php application

Publish Date:2025/03/26 Views:131 Category:Docker

I'm learning docker recently. I'm learning by building an nginx+php development environment example. Here I record the build process. First, give a docker-compose.yml deployment configuration file version: '3' services: nginx: container_nam

How to use Docker to image a Node.js web application

Publish Date:2025/03/26 Views:107 Category:Docker

Docker is a containerization platform that simplifies the packaging and execution of applications. Containers run as independent processes with their own file systems, but share the kernel of their host machine. Docker has attracted much at

Start a Bash terminal in a new Docker container

Publish Date:2025/03/26 Views:97 Category:Docker

Docker containers are a standard unit for packaging all the dependencies of an application, allowing us to easily run them in any environment. Containers have become very popular recently, and most developers now rely heavily on containers

Passing environment variables to containers in Docker

Publish Date:2025/03/26 Views:125 Category:Docker

This article will introduce how to pass environment variables to containers in Docker. Passing environment variables to containers in Docker using the -e and tags -env We will first see how to create environment variables and pass them to t

Install Docker using Homebrew

Publish Date:2025/03/26 Views:202 Category:Docker

There is no doubt that Docker containers have revolutionized the way we develop and deploy applications. They provide developers with the ability to package applications and dependencies in an isolated environment. Recently, we've seen wide

Enforce clean build of images in Docker

Publish Date:2025/03/26 Views:88 Category:Docker

This article discusses and demonstrates how to enforce clean builds of images in Docker. Building images in Docker We will use a simple Flask application to demonstrate this concept. my-app Create a app.py simple application named in the ho

Running a Docker instance from a Dockerfile

Publish Date:2025/03/26 Views:140 Category:Docker

Docker containers have undoubtedly become the standard unit for managing software and dependencies in different environments. When using real applications, you must create a docker file before building the container image of the application

Scan to Read All Tech Tutorials

Social Media
  • https://www.github.com/onmpw
  • qq:1244347461

Recommended

Tags

Scan the Code
Easier Access Tutorial