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

Copy files from host to Docker container

Publish Date:2025/03/25 Views:126 Category:Docker

This article will discuss and demonstrate methods we can use to transfer files from the host to a running container in Docker. docker cp Copy the file from the host to the Docker container using docker cp The command is one of the simplest

Get the IP address of the Docker container

Publish Date:2025/03/25 Views:102 Category:Docker

This article demonstrates how to get the IP address of a Docker container. Connect to the Bridge network and get the IP address of the Docker container One of the big reasons why docker containers are so convenient is that we can easily con

Uninstalling Docker on macOS

Publish Date:2025/03/25 Views:95 Category:Docker

Recently, we have seen widespread adoption of Docker as the ultimate containerization platform. Because of this, setting up Docker on all platforms has been greatly simplified, including macOS and Windows. However, some users usually face p

Enter the Docker container's shell

Publish Date:2025/03/25 Views:98 Category:Docker

This article will demonstrate how to enter the Docker container shell using multiple methods. Use docker exec to enter the Docker container's shell We need to have a container up and running to use this command. We can check the status of t

Listing containers in Docker

Publish Date:2025/03/25 Views:122 Category:Docker

This article will discuss various commands for listing containers created in our system. This means we should create some containers beforehand for these commands to return values. List all running containers in Docker We will start by list

Mount the host directory into the Docker container

Publish Date:2025/03/25 Views:189 Category:Docker

Docker provides, among other features, tools to work with the host operating system and the container file system. One of these features is the ability to persist data in containers and share data between containers by mounting directories

Docker build command with multiple parameters

Publish Date:2025/03/25 Views:138 Category:Docker

docker build The command allows us to create a Docker image from a Dockerfile. It also allows us to build an image from a context that references a set of files located in a location specified by a PATH or URL. A Dockerfile, on the other ha

The difference between CMD and ENTRYPOINT in Docker

Publish Date:2025/03/25 Views:141 Category:Docker

Docker containers have become the standard when it comes to managing software and dependencies in different environments. When working with real-world applications, you need to create a docker file before building your application container

Scan to Read All Tech Tutorials

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

Recommended

Tags

Scan the Code
Easier Access Tutorial