容器化一个应用
参考: https://docs.docker.com/get-started/
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.json[root@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.jsonfile, create a file namedDockerfile. You can use the following commands below to create aDockerfilebased 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 buildcommand 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-alpineimage. 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
Dockerfilecopied in your application and useyarnto install your application’s dependencies. TheCMDdirective specifies the default command to run when starting a container from this image.finally, the
-tflag 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 buildcommand tell the docker that it should look for theDockerfilein 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 runcommand and specify the name of the image you just created:docker run -d -p 3000:3000 getting-startedYou use the
-dflag to run the new container in “detached” mode(in the background). You also use the-pflag 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.
发表回复