容器化一个应用
For the rest of this guide, you will be working with a simple todo list manager
Get the app
运行运用之前,你需要下载源码到你的主机上。
-
克隆仓库:
git clone https://github.com/docker/getting-started.git
-
进入
getting-started/app
下, 可以看到spec文件夹、src文件夹、和package.jsonroot@localhost getting-started]# tree [. app ├── package.json │ ├── spec │ ├── | └──//... src │ ├── //... │ └──yarn.lock │ └── //...
Build the app’s image
In order to build hte container image, you’ll need to use a Dockerfile
. A Dockerfile
is simply a text-based file with no file extension. A Dockerfile
contains a script of instructions that Docker uses to create a container image.
-
In the app directory, the same location as the
package.json
file, create a file namedDockerfile
. You can use the following commands below to create aDockerfile
based on your operating system.for linux:
root@localhost getting-started]# pwd [/root/docker/getting-started root@localhost getting-started]# cd app [root@localhost getting-started]# touch Dockerfile [root@localhost getting-started]# vim Dockerfile [
编辑内容,内容如下
# syntax=docker/dockerfile:1 FROM node:18-alpine WORKDIR /app COPY . . RUN yarn install --production CMD ["node", "src/index.js"] EXPOSE 3000
-
Build the container image using the following commands
先进入app目录(
Dockerfile
所在目录)root@localhost app]# cd /root/docker/getting-started/app [
然后执行如下命令构建镜像
docker build -t getting-started .
The
docker build
command uses the Dockerfile to build a new container image. You might have noticed that Docker downloaded a lot of “layers”. The is because you instructed the builder that you wanted to start fromnode:18-alpine
image. But, since you didn’t have that on your machine, Docker needed to download the image.After Docker downloaded the image, the instructions from the
Dockerfile
copied in your application and useyarn
to install your application’s dependencies. TheCMD
directive specifies the default command to run when starting a container from this image.finally, the
-t
flag tags your image. Think of this simply as a hunman-readable name from the final image. Since you named the imagegetting-started
, you can refer to that image when you run a container.The
.
at the end of thedocker build
command tell the docker that it should look for theDockerfile
in the current directory.
Start an app container
Now that you have an image, you can run the application in a container. To do so, you will use the docker run
command.
-
Start your container using the
docker run
command and specify the name of the image you just created:docker run -d -p 3000:3000 getting-started
You use the
-d
flag to run the new container in “detached” mode(in the background). You also use the-p
flag to create a mapping between the host’s port 3000 to the container’s port 3000. Without the port mapping, you wouldn’t be able to access the application. -
After a few seconds, open your web browser to
http://<your_machine_ip>:3000
, you should see you app.
发表回复