接下来我们来看看更复杂的东西,如何在docker中启动一个nginx并且在本地去访问它:
尝试输入下面的命令:
docker run nginx
然后得到如下输出:
Unable to find image 'nginx:latest' locally latest: Pulling from library/nginx bc95e04b23c0: Pull complete f3186e650f4e: Pull complete 9ac7d6621708: Pull complete Digest: sha256:b81f317384d7388708a498555c28a7cce778a8f291d90021208b3eba3fe74887 Status: Downloaded newer image for nginx:latest
因为nginx是一个服务,而且我们也没有指定后台运行,所以控制台没有任何输出,也没有自动退出,我们需要按下 ctrl + c 来强制中断进程。
查看本地有哪些镜像:
docker images
可以看到如下输出:
REPOSITORY TAG IMAGE ID CREATED SIZE nginx latest9e7424e5dbae 2 weeks ago 108MB ubuntulatest20c44cd7596f 3 weeks ago 123MB
那么我们如何将nginx在后台运行,并且访问docker中的nginx服务呢?
docker run -p 8080:80 -d nginx
运行以后我们得到了一串很长的字符串:
307f315009bebee302ee70b3e9eb2002a6ff5f4ddfa37f038be0551b95de4e09
输入命令来查看一下当前都有哪些docker在运行:
docker ps
看到如下输入:
ConTAINER ID IMAGE COMMAND CREATED STATUSPORTS NAMES 307f315009be nginx "nginx -g 'daemon of…" 53 seconds ago Up 51 seconds0.0.0.0:8080->80/tcp fervent_austin
其中 ConTAINER ID 就是我们刚才得到的一大长串输入的前几位
让我们验证一下 nginx 是否成功启动:
curl 127.0.0.1:8080
会看到如下输出:
Welcome to nginx!
body {
width: 35em;
margin: 0 auto;
font-family: Tahoma, Verdana, Arial, sans-serif;
}
Welcome to nginx!
If you see this page, the nginx web server is successfully installed and
working. Further configuration is required.
For online documentation and support please refer to
nginx.org.
Commercial support is available at
nginx.com.
Thank you for using nginx.
说明我们的nginx已经启动成功了~
如果是在本机运行,或者是在虚拟机运行,也可以通过虚拟机或者本机的IP直接访问 8080 端口来在浏览器直接访问,如果无法访问可以检查防火墙是不是没有开启 8080 端口。



