aliyun
sudo yum-config-manager --add-repo http://mirrors.aliyun.com/docker-ce/linux/centos/docker-ce.repo
清华大学
sudo yum-config-manager --add-repo https://mirrors.tuna.tsinghua.edu.cn/docker-ce/linux/centos/docker-ce.repo
我们通过 docker 的两个参数 -i -t,让 docker 运行的容器实现**“对话”**的能力:
runoob@runoob:~$ docker run -i -t ubuntu:15.10 /bin/bash
root@0123ce188bd8:/#
各个参数解析:
我们可以通过运行 exit 命令或者使用 CTRL+D 来退出容器。
root@0123ce188bd8:/# exit
exit
root@runoob:~#
使用yaml文件格式创建容器,管理容器
以下是全部的命令
Define and run multi-container applications with Docker.
Usage:
docker-compose [-f <arg>...] [options] [COMMAND] [ARGS...]
docker-compose -h|--help
Options:
-f, --file FILE Specify an alternate compose file (default: docker-compose.yml) 指定一个让docker 选择的文件,默认名字是 dicker-compose.yml,这就是提供的文件
-p, --project-name NAME Specify an alternate project name (default: directory name)
--verbose Show more output
--no-ansi Do not print ANSI control characters
-v, --version Print version and exit
-H, --host HOST Daemon socket to connect to
--tls Use TLS; implied by --tlsverify
--tlscacert CA_PATH Trust certs signed only by this CA
--tlscert CLIENT_CERT_PATH Path to TLS certificate file
--tlskey TLS_KEY_PATH Path to TLS key file
--tlsverify Use TLS and verify the remote
--skip-hostname-check Don't check the daemon's hostname against the name specified
in the client certificate (for example if your docker host
is an IP address)
--project-directory PATH Specify an alternate working directory
(default: the path of the Compose file)
Commands:
build Build or rebuild services
bundle Generate a Docker bundle from the Compose file
config Validate and view the Compose file
create Create services
down Stop and remove containers, networks, images, and volumes
events Receive real time events from containers
exec Execute a command in a running container
help Get help on a command
images List images
kill Kill containers
logs View output from containers
pause Pause services
port Print the public port for a port binding
ps List containers
pull Pull service images
push Push service images
restart Restart services
rm Remove stopped containers
run Run a one-off command
scale Set number of containers for a service
start Start services
stop Stop services
top Display the running processes
unpause Unpause services
up Create and start containers
version Show the Docker-Compose version information
在指定目录下创建docker-compose.yml文件,内容如下:
version: '3.1'
services:
mysql:
image: mysql:5.7
restart: always
environment:
MYSQL_ROOT_PASSWORD: 123456
TZ: Asia/Shanghai
volumes:
- ./mysql/logs:/var/log/mysql/
- /mysql/mydata:/var/lib/mysql
- /mysql/conf.d:/etc/mysql/conf.d
ports:
- "3306:3306"
在该目录下,新建目录和文件:/mysql/logs 、/mysql/mydata、/mysql/conf.d 三个目录,在该目录下直接使用 docker-compose up -d mysql 指向docker-compose.yml中 service下的mysq
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0modelVersion>
<parent>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-parentartifactId>
<version>2.3.5.RELEASEversion>
<relativePath/>
parent>
<groupId>com.examplegroupId>
<artifactId>docker_imagesartifactId>
<version>0.0.1-SNAPSHOTversion>
<name>docker_imagesname>
<description>Demo project for Spring Bootdescription>
<properties>
<java.version>1.8java.version>
properties>
<dependencies>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-webartifactId>
dependency>
<dependency>
<groupId>com.github.xiaoymingroupId>
<artifactId>swagger-bootstrap-uiartifactId>
<version>1.9.6version>
dependency>
<dependency>
<groupId>io.springfoxgroupId>
<artifactId>springfox-swagger2artifactId>
<version>2.9.2version>
dependency>
<dependency>
<groupId>org.projectlombokgroupId>
<artifactId>lombokartifactId>
<optional>trueoptional>
dependency>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-testartifactId>
<scope>testscope>
<exclusions>
<exclusion>
<groupId>org.junit.vintagegroupId>
<artifactId>junit-vintage-engineartifactId>
exclusion>
exclusions>
dependency>
dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-maven-pluginartifactId>
plugin>
plugins>
build>
project>
## 1. 引入swagger是方便测试
package com.example.docker_images.config;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
/**
* @author Javacfox
*/
@Configuration
@EnableSwagger2
public class Swagger2Config {
/**
* 设置swagger跨域,提供给service调用
* @return
*/
@Bean
public WebMvcConfigurer crossConfigurer(){
WebMvcConfigurer webMvcConfigurerAdapter = new WebMvcConfigurer() {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/v2/api-docs");
registry.addMapping("/**");
}
};
return webMvcConfigurerAdapter;
}
@Bean
public Docket createRestApi(){
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()
//基础扫描包路径
.apis(RequestHandlerSelectors.basePackage("com.example.docker_images.controller"))
.paths(PathSelectors.any())
.build();
}
private ApiInfo apiInfo(){
return new ApiInfoBuilder()
.title("java")
.description("java项目打包成docker images并运行")
.version("1.0.0")
.build();
}
private CorsConfiguration buildConfig() {
CorsConfiguration corsConfiguration = new CorsConfiguration();
// 1允许任何域名使用
corsConfiguration.addAllowedOrigin("*");
// 2允许任何头
corsConfiguration.addAllowedHeader("*");
// 3允许任何方法(post、get等)
corsConfiguration.addAllowedMethod("*");
return corsConfiguration;
}
@Bean
public CorsFilter corsFilter() {
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", buildConfig());
return new CorsFilter(source);
}
}
# 2. 接口编写
package com.example.docker_images.controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/hello")
public class HelloController {
@GetMapping("/sayHello")
public String say(String userName){
return "hello,"+userName+"!";
}
}
# 3. 主类
package com.example.docker_images;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class DockerImagesApplication {
public static void main(String[] args) {
SpringApplication.run(DockerImagesApplication.class, args);
}
}
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113
上面是所有的java项目,非常简单,目前只是为了测试。
# 以jdk8为基础镜像
FROM openjdk:8
# 描述
LABEL description="Java 8"
# 暴露接口
EXPOSE 8088
# 将主机中的jar包添加到镜像中
ADD /docker_images-0.0.1-SNAPSHOT.jar docker_images-0.0.1-SNAPSHOT.jar
# 运行jar包
ENTRYPOINT ["java", "-jar","docker_images-0.0.1-SNAPSHOT.jar"]
1234567891011
version: '3'
services:
test:
container_name: java_test #配置容器名
build:
context: .
dockerfile: DockerFile #指定dockerFile文件
image: java/test:8.0.0 # 指定镜像名
ports:
- "8080:8080"# 暴露端口
volumes:
- /logs:/logs # 创建容器数据卷123456789101112
[root@192 ~]# cd /root/docker_image
[root@192 docker_image]# ll
total 26384
-rw-r--r--. 1 root root 217 Nov 15 20:08 docker-compose.yml
-rw-r--r--. 1 root root 188 Nov 15 04:32 DockerFile
-rw-r--r--. 1 root root 27005222 Nov 12 10:27 docker_images-0.0.1-SNAPSHOT.jar
[root@192 docker_image]# docker-compose build
Building test
Step 1/5 : FROM openjdk:8
Trying to pull repository docker.io/library/openjdk ...
8: Pulling from docker.io/library/openjdk
e4c3d3e4f7b0: Pull complete
101c41d0463b: Pull complete
8275efcd805f: Pull complete
751620502a7a: Pull complete
a59da3a7d0e7: Pull complete
5ad32ac1e527: Pull complete
7ee60316f31a: Pull complete
Digest: sha256:44713efa363430c6d991f59bbc47238838ecf09a2df4dfb8bbbb07a55f8aeeae
Status: Downloaded newer image for docker.io/openjdk:8
---> 192ceee8f2fd
Step 2/5 : LABEL description "Java 8"
---> Running in 4b14bbeddd1d
---> 1b5324a856ad
Removing intermediate container 4b14bbeddd1d
Step 3/5 : EXPOSE 8088
---> Running in e08c74d7f0dd
---> bb0a7991cb0e
Removing intermediate container e08c74d7f0dd
Step 4/5 : ADD /docker_images-0.0.1-SNAPSHOT.jar docker_images-0.0.1-SNAPSHOT.jar
---> 8fa5fc5834ff
Removing intermediate container 32c95ff2d8a0
Step 5/5 : ENTRYPOINT java -jar docker_images-0.0.1-SNAPSHOT.jar
---> Running in c40f5144492f
---> b7258eff2bc4
Removing intermediate container c40f5144492f
Successfully built b7258eff2bc4
[root@192 docker_image]# docker-compose up -d
Creating java_test ... done
[root@192 docker_image]# docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
61551d9dbee7 java/test:8.0.0 "java -jar docker_..." 7 seconds ago Up 7 seconds 0.0.0.0:8088->8088/tcp java_test
12345678910111213141516171819202122232425262728293031323334353637383940414243
步骤解说:
docker-compose build
docker-compose up -d
docker拉取mysql镜像速度很慢
1. sysuygm@sysuygm:~$ docker pull mysql:5.7
5.7: Pulling from library/mysql
85b1f47fba49: Pulling fs layer
5671503d4f93: Download complete
3b43b3b913cb: Download complete
4fbb803665d0: Waiting
05808866e6f9: Waiting
1d8c65d48cfa: Waiting
e189e187b2b5: Waiting
02d3e6011ee8: Waiting
2d0f3914273e: Waiting
b7de9fbb86ba: Waiting
error pulling image configuration: Get https://registry-1.docker.io/v2/library/mysql/blobs/sha256:dd0afb9bc4a99c70cdda8002ef2f1816405a795ee28faa0debd633f3380f8c4c: dial tcp 34.225.121.244:443: i/o timeout
sysuygm@sysuygm:~$ docker pull mysql:5.7
Error response from daemon: Get https://registry-1.docker.io/v2/library/mysql/manifests/5.7: Get https://auth.docker.io/token?scope=repository%3Alibrary%2Fmysql%3Apull&service=registry.docker.io: net/http: request canceled while waiting for connection (Client.Timeout exceeded while awaiting headers)
sysuygm@sysuygm:~$ docker pull mysql:5.7
Error response from daemon: Get https://registry-1.docker.io/v2/: net/http: request canceled while waiting for connection (Client.Timeout exceeded while awaiting headers)
sysuygm@sysuygm:~$ docker pull mysql:5.7
5.7: Pulling from library/mysql
Get https://registry-1.docker.io/v2/library/mysql/manifests/sha256:94ed2fa3857cc98ec8d680aedfd5a05ea5a3ea954f062edbdc0443d0f53a428e: dial tcp 54.152.209.167:443: i/o timeout
sysuygm@sysuygm:~$ docker pull mysql:5.7
Error response from daemon: Get https://registry-1.docker.io/v2/library/mysql/manifests/5.7: dial tcp 34.200.28.105:443: i/o timeout
sysuygm@sysuygm:~$ docker pull mysql:5.7
Error response from daemon: Get https://registry-1.docker.io/v2/: net/http: request canceled while waiting for connection (Client.Timeout exceeded while awaiting headers)
sysuygm@sysuygm:~$ docker pull mysql:5.7
Error response from daemon: Get https://registry-1.docker.io/v2/: net/http: request canceled while waiting for connection (Client.Timeout exceeded while awaiting headers)
sysuygm@sysuygm:~$ docker pull mysql:5.7
Error response from daemon: Get https://registry-1.docker.io/v2/library/mysql/manifests/5.7: Get https://auth.docker.io/token?scope=repository%3Alibrary%2Fmysql%3Apull&service=registry.docker.io: net/http: request canceled while waiting for connection (Client.Timeout exceeded while awaiting headers)
2. sysuygm@sysuygm:~$ docker pull daocloud.io/library/centos:latest
latest: Pulling from library/centos
d9aaf4d82f24: Downloading [> ]
sysuygm@sysuygm:~$ docker pull daocloud.io/library/mysql:5.7
5.7: Pulling from library/mysql
85b1f47fba49: Pull complete
5671503d4f93: Pull complete
3b43b3b913cb: Pull complete
4fbb803665d0: Pull complete
05808866e6f9: Pull complete
1d8c65d48cfa: Pull complete
e189e187b2b5: Pull complete
02d3e6011ee8: Pull complete
d43b32d5ce04: Pull complete
2a809168ab45: Pull complete
Digest: sha256:a0423a7d021b7a7775f1d2db1014bd15fde029f538c1f8d97c9832aa4a25209f
Status: Downloaded newer image for daocloud.io/library/mysql:5.7
sysuygm@sysuygm:~$ docker images
REPOSITORY TAG IMAGE ID CREATED SIZE
hello-world latest f2a91732366c 2 weeks ago 1.85kB
daocloud.io/library/mysql 5.7 5709795eeffa 5 weeks ago 408MB
需要注意的是:mysql镜像名的前缀不能忘记,否则报错!
完整的名字: daocloud.io/library/mysql:5.7
sysuygm@sysuygm:~$ docker run -p 3306:3306 --name mysql2 -e MYSQL_ROOT_PASSWORD=root -d mysql:5.7
Unable to find image 'mysql:5.7' locally
docker: Error response from daemon: Get https://registry-1.docker.io/v2/library/mysql/manifests/5.7: Get https://auth.docker.io/token?scope=repository%3Alibrary%2Fmysql%3Apull&service=registry.docker.io: net/http: request canceled while waiting for connection (Client.Timeout exceeded while awaiting headers).
See 'docker run --help'.
sysuygm@sysuygm:~$ docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
sysuygm@sysuygm:~$ docker run -it --net host daocloud.io/library/mysql:5.7 "sh"
方法一可以直接拉取镜像,但是docker-compose
进入虚拟机修改docker配置
vim /etc/docker/daemon.json`
编辑代码
`{ "registry-mirrors": ["https://nsodgxr5.mirror.aliyuncs.com"] }`
重启docker
`sudo systemctl daemon-reload`
`sudo systemctl restart docker
docker chown: changing ownership of ‘/var/lib/XXX’: Permission denied
Links:
1.entos7下docker Permission denied
2.查看 SELinux状态及关闭SELinux
方法:
1.查看SELinux状态
sestatus -v
getenforce
2.临时关闭SELinux
setenforce 0
docker chown: changing ownership of '/var/lib/XXX': Permission denied
1.entos7下docker Permission denied
在centos的docker上安装mysql提示chown mod /var/lib/mysql permission denied,通过下面的方法1解决。
在centos上挂载数据卷,在容器内部访问数据卷的时候报permission denied出错,通过下面的方法1解决。
1.Centos7安全Selinux禁止了一些安全权限,导致mysql和mariadb在进行挂载/var/lib/mysql的时候会提示如下信息:
复制代码
1 [root@localhost mariadb]# docker run -d -v ~/mariadb/data/:/var/lib/mysql -v ~/mariadb/config/:/etc/mysql/conf.d -e MYSQL_ROOT_PASSWORD=‘123456‘ test01/mariadb
2 19c4aa113c610f53f9720ee806e3c918dd18d21dff75c043bdd6db60011a135d
3 [root@localhost mariadb]# docker ps -a
4 CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
5 19c4aa113c61 test01/mariadb "docker-entrypoint.sh" 4 seconds ago Exited (1) 1 seconds ago desperate_kelle
复制代码
logs命令查看,发现提示信息是:chown: changing ownership of ‘/var/lib/mysql/....‘: Permission denied
于是,解决方法有这么三个:
在docker run中加入 --privileged=true 给容器加上特定权限
关闭selinux
在selinux添加规则,修改挂载目录de
2. 有时候,在启动带有端口映射的容器时候,会出现如下提示:
1 iptables failed: iptables --wait -t nat -A DOCKER -p tcp -d 0/0 --dport 52080 -j DNAT --to-destination 192.168.222.222:2080 ! -i docker0: iptables: No chain/target/match by that name
这玩意,查来查去也没给解释,参考了下http://www.lxy520.net/2015/09/24/centos-7-docker-qi-dong-bao/,这篇文章说要修改iptables的文件,只是centos7有可能根本就没有这个文件,或者没有装iptables的服务,结果最后重启宿主机,恢复了,期间尝试使用firewall-cmd命令查询,和停止防火墙。此思路供后人参考。
2.查看 SELinux状态及关闭SELinux
方法:
1.查看SELinux状态
sestatus -v
getenforce
2.临时关闭SELinux
setenforce 0
docker logs -f -t --since="2017-05-31" --tail=10 edu_web_1
edu_web_1 为容器名,也可用容器 id 。
docker logs [OPTIONS] CONTAINER
Options:
--details 显示更多的信息
-f, --follow 实时输出日志,最后一行为当前时间戳的日志
--since string 输出日志开始日期,即只输出指定日期之后的日志。
--tail string 显示最后多少行日志, 默认是all
(如: -tail=10 : 查看最后的 10 行日志。)
-t, --timestamps 显示时间戳
docker logs 26b12d17fefc
输出日志内容:
nohup: appending output to 'nohup.out'
nohup: appending output to 'nohup.out'
docker logs -t 26b12d17fefc
输出日志内容:
2017-07-03T12:12:29.909710295Z nohup: appending output to 'nohup.out'
2017-07-03T13:58:54.232003809Z nohup: appending output to 'nohup.out'
docker logs --tail 1 26b12d17fefc
输出日志内容:
nohup: appending output to 'nohup.out'
docker logs -t --tail 1 26b12d17fefc
输出日志内容:
2017-07-03T13:58:54.232003809Z nohup: appending output to 'nohup.out'
docker logs --since 30m 26b12d17fefc
输出日志内容:
nohup: appending output to 'nohup.out'
docker logs -t --since="2017-07-03T13:58:54.232003809Z" 26b12d17fefc
输出日志内容:
2017-07-03T13:58:54.232003809Z nohup: appending output to 'nohup.out'
docker logs -t --since="2017-07-03T12:12:29.909710295Z" 26b12d17fefc
输出日志内容:
2017-07-03T12:12:29.909710295Z nohup: appending output to 'nohup.out'
2017-07-03T13:58:54.232003809Z nohup: appending output to 'nohup.out'
容器日志的输出形式
“Docker Daemon是Docker架构中一个常驻在后台的系统进程,它在后台启动了一个Server,Server负责接受Docker Client发送的请求;接受请求后,Server通过路由与分发调度,找到相应的Handler来执行请求。–《Docker源码分析》”
当我们输入 docker logs 的时候会转化为 Docker Client 向 Docker Daemon 发起请求,。
Docker Daemon 在运行容器时会去创建一个协程(goroutine),绑定了整个容器内所有进程的标准输出文件描述符。
因此容器内应用的所有只要是标准输出日志,都会被 goroutine 接收。
Docker Daemon 会根据容器 id 和日志类型读取日志内容,最终会输出到用户终端上并且通过 json 格式存放在/var/lib/docker/containers目录下。
docker logs是跟随容器而产生的,如果删除了某个容器,相应的日志文件也会随着被删除。
docker-compose up -d nginx 构建建启动nignx容器
docker-compose exec nginx bash 登录到nginx容器中
docker-compose down 删除所有nginx容器,镜像
docker-compose ps 显示所有容器
docker-compose restart nginx 重新启动nginx容器
docker-compose run --no-deps --rm php-fpm php -v 在php-fpm中不启动关联容器,并容器执行php -v 执行完成后删除容器
docker-compose build nginx 构建镜像 。
docker-compose build --no-cache nginx 不带缓存的构建。
docker-compose logs nginx 查看nginx的日志
docker-compose logs -f nginx 查看nginx的实时日志
docker-compose config -q 验证(docker-compose.yml)文件配置,当配置正确时,不输出任何内容,当文件配置错误,输出错误信息。
docker-compose events --json nginx 以json的形式输出nginx的docker日志
docker-compose pause nginx 暂停nignx容器
docker-compose unpause nginx 恢复ningx容器
docker-compose rm nginx 删除容器(删除前必须关闭容器)
docker-compose stop nginx 停止nignx容器
docker-compose start nginx 启动nignx容器
我们都知道docker容器之间是互相隔离的,不能互相访问,但如果有些依赖关系的服务要怎么办呢。下面介绍三种方法解决容器互访问题。
安装docker时,docker会默认创建一个内部的桥接网络docker0,每创建一个容器分配一个虚拟网卡,容器之间可以根据ip互相访问。
[root@33fcf82ab4dd /]# [root@CentOS ~]# ifconfig
......
docker0: flags=4163 mtu 1500
inet 172.17.0.1 netmask 255.255.0.0 broadcast 0.0.0.0
inet6 fe80::42:35ff:feac:66d8 prefixlen 64 scopeid 0x20
ether 02:42:35:ac:66:d8 txqueuelen 0 (Ethernet)
RX packets 4018 bytes 266467 (260.2 KiB)
RX errors 0 dropped 0 overruns 0 frame 0
TX packets 4226 bytes 33935667 (32.3 MiB)
TX errors 0 dropped 0 overruns 0 carrier 0 collisions 0
......
运行一个centos镜像, 查看ip地址得到:172.17.0.7
[root@CentOS ~]# docker run -it --name centos-1 docker.io/centos:latest
[root@6d214ff8d70a /]# ifconfig
eth0: flags=4163 mtu 1500
inet 172.17.0.7 netmask 255.255.0.0 broadcast 0.0.0.0
inet6 fe80::42:acff:fe11:7 prefixlen 64 scopeid 0x20
ether 02:42:ac:11:00:07 txqueuelen 0 (Ethernet)
RX packets 16 bytes 1296 (1.2 KiB)
RX errors 0 dropped 0 overruns 0 frame 0
TX packets 8 bytes 648 (648.0 B)
TX errors 0 dropped 0 overruns 0 carrier 0 collisions 0
以同样的命令再起一个容器,查看ip地址得到:172.17.0.8
[root@CentOS ~]# docker run -it --name centos-2 docker.io/centos:latest
[root@33fcf82ab4dd /]# ifconfig
eth0: flags=4163 mtu 1500
inet 172.17.0.8 netmask 255.255.0.0 broadcast 0.0.0.0
inet6 fe80::42:acff:fe11:8 prefixlen 64 scopeid 0x20
ether 02:42:ac:11:00:08 txqueuelen 0 (Ethernet)
RX packets 8 bytes 648 (648.0 B)
RX errors 0 dropped 0 overruns 0 frame 0
TX packets 8 bytes 648 (648.0 B)
TX errors 0 dropped 0 overruns 0 carrier 0 collisions 0
容器内部ping测试结果如下:
[root@33fcf82ab4dd /]# ping 172.17.0.7
PING 172.17.0.7 (172.17.0.7) 56(84) bytes of data.
64 bytes from 172.17.0.7: icmp_seq=1 ttl=64 time=0.205 ms
64 bytes from 172.17.0.7: icmp_seq=2 ttl=64 time=0.119 ms
64 bytes from 172.17.0.7: icmp_seq=3 ttl=64 time=0.118 ms
64 bytes from 172.17.0.7: icmp_seq=4 ttl=64 time=0.101 ms
这种方式必须知道每个容器的ip,在实际使用中并不实用。
运行容器的时候加上参数link
运行第一个容器
docker run -it --name centos-1 docker.io/centos:latest
运行第二个容器
[root@CentOS ~]# docker run -it --name centos-2 --link centos-1:centos-1 docker.io/centos:latest
–link:参数中第一个centos-1是容器名,第二个centos-1是定义的容器别名(使用别名访问容器),为了方便使用,一般别名默认容器名。
测试结果如下:
[root@e0841aa13c5b /]# ping centos-1
PING centos-1 (172.17.0.7) 56(84) bytes of data.
64 bytes from centos-1 (172.17.0.7): icmp_seq=1 ttl=64 time=0.210 ms
64 bytes from centos-1 (172.17.0.7): icmp_seq=2 ttl=64 time=0.116 ms
64 bytes from centos-1 (172.17.0.7): icmp_seq=3 ttl=64 time=0.112 ms
64 bytes from centos-1 (172.17.0.7): icmp_seq=4 ttl=64 time=0.114 ms
此方法对容器创建的顺序有要求,如果集群内部多个容器要互访,使用就不太方便。
1.安装好docker后,运行如下命令创建bridge网络:docker network create testnet
查询到新创建的bridge testnet。
2.运行容器连接到testnet网络。
使用方法:docker run -it --name <容器名> —network --network-alias <网络别名> <镜像名>
[root@CentOS ~]# docker run -it --name centos-1 --network testnet --network-alias centos-1 docker.io/centos:latest
[root@CentOS ~]# docker run -it --name centos-2 --network testnet --network-alias centos-2 docker.io/centos:latest
3.从一个容器ping另外一个容器,测试结果如下:
[root@fafe2622f2af /]# ping centos-1
PING centos-1 (172.20.0.2) 56(84) bytes of data.
64 bytes from centos-1.testnet (172.20.0.2): icmp_seq=1 ttl=64 time=0.158 ms
64 bytes from centos-1.testnet (172.20.0.2): icmp_seq=2 ttl=64 time=0.108 ms
64 bytes from centos-1.testnet (172.20.0.2): icmp_seq=3 ttl=64 time=0.112 ms
64 bytes from centos-1.testnet (172.20.0.2): icmp_seq=4 ttl=64 time=0.113 ms
4.若访问容器中服务,可以使用这用方式访问 <网络别名>:<服务端口号>
推荐使用这种方法,自定义网络,因为使用的是网络别名,可以不用顾虑ip是否变动,只要连接到docker内部bright网络即可互访。bridge也可以建立多个,隔离在不同的网段。
启动后配置阿里云服务器安全组开放映射的端口
docker run -id -p 3307:3306 \
--name=my1 \
--network testnet \
--network-alias my1 \
-v $PWD/conf/myconf.d:/etc/mysql/conf.d \
-v $PWD/logs:/logs \
-v $PWD/data:/var/lib/mysql \
-e MYSQL_ROOT_PASSWORD=root \
mysql:5.6
docker run -it \
--name=my2 \
--network testnet \
--network-alias my2 \
centos:7 \
bash
脚本
import pymysql
db = pymysql.connect("120.78.72.136","root","root","docker",port=3307)
cursor = db.cursor()
cursor.execute("SELECT * FROM test")
data = cursor.fetchone()
print (data)
db.close()
`# ip为宿主机ip 端口为容器映射到宿主机的端口`
s1容器放mysql服务,s2容器放一个python脚本能够查询s1容器内mysql数据库的内容
docker run -id -p 3307:3306 \
--name=s1 \
--network testnet \
--network-alias s1 \
-v $PWD/conf/myconf.d:/etc/mysql/conf.d \
-v $PWD/logs:/logs \
-v $PWD/data:/var/lib/mysql \
-e MYSQL_ROOT_PASSWORD=root \
mysql:5.6
容器端口3306映射宿主机端口3307,对外开放3307端口,若想让外部访问需配置安全组开放3307端口
docker exec -it s1 bash # 进入容器内
mysql -uroot -proot # 进入mysql数据库 创建库和表
容器创建
docker run -it \
--name=my2 \
--network testnet \
--network-alias my2 \
centos:7 \
bash
脚本创建
import pymysql
db = pymysql.connect("s1","root","root","docker",port=3306)
cursor = db.cursor()
cursor.execute("SELECT * FROM test")
data = cursor.fetchone()
print (data)
db.close()
# s1 为网络别名 在我们创建容器时创建
# 3306 容器内的服务端口号
例子:用dockerfile创建一个包含jdk和tomcat的镜像
里就不在赘述docker的一些基础应用了直接上步骤:
1.第一步需要在宿主机上创建一个文件夹(/opt/centos的文件目录)
2.将tomcat和jdk上传到宿主机上。(如图)
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-5i7EIoWk-1627259463851)(D:\开发\20190530135723159.png)]
注:上面都是准备工作,这里就不一一详细赘述了。
3.在当前文件夹下面创建一个dockerfile文件,文件内容如下.
![20190530140127893](D:\开发\20190530140127893.png)#镜像
FROM centos
#创建者
MAINTAINER gl.com
#工作目录
WORKDIR /root
#在/opt/下创建jdk目录,用来存放jdk文件
RUN mkdir /opt/jdk
#在/opt/下创建tomcat目录,用来存放tomcat
RUN mkdir /opt/tomcat
#将宿主机的jdk目录下的文件拷至镜像的/opt/jdk目录下
COPY jdk1.8.0_201 /opt/jdk/
#将宿主机的tomcat目录下的文件拷至镜像的/opt/tomcat目录下
COPY apache-tomcat-8.5.32 /opt/tomcat/vim
#设置环境变量
ENV JAVA_HOME=/opt/jdk
ENV JRE_HOME=$JAVA_HOME/jre
ENV CLASSPATH=.:$JAVA_HOME/lib/dt.jar:$JAVA_HOME/lib/tools.jar:$JRE_HOME/lib:$CLASSPATH
ENV PATH=/sbin:$JAVA_HOME/bin:$PATH
#公开端口
EXPOSE 8080
#设置启动命令
ENTRYPOINT ["/opt/tomcat/bin/catalina.sh","run"]
4.运行dockerfile文件生成docker镜像,命令:docker build -t centos .
成功命令:
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-ztD6D1pk-1627259463852)(D:\开发\20190530140127893.png)]
5.这里就生成了镜像文件,我们通过命令:docker images 查看镜像
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-J2PqWrZg-1627259463855)(D:\开发\20190530140220262.png)]
nginx nodejs环境配置_基于docker的nodejs、php开发环境,包含多种组合安装
dnnmmp
基于docker的nodejs、php开发环境 (docker,nodejs,php,nginx,mongo,mysql,redis)
Dnnmmp包含以下组合
dnm(Docker + Nodejs + Mysql/MongoDB/Redis)
dnmn(Docker + Nodejs + Mysql/MongoDB/Redis + Nginx)
dnmp(Docker + Nginx + Mysql/MongoDB/Redis + PHP)
支持系统版本:Linux、MacOs、Windows
特性
1.主要针对nodejs开发人员、php开发人员,运维,前端
2.支持多版本php,nodejs
3.兼容OneinStack的配置文件,完善的配置说明
4.支持绑定多个域名
5.清晰的docker文件、配置文件、日志文件结构
6.支持php扩展安装
7.程序是基于docker最新stable版,并从官方仓库下载
8.持续不断更新,支持交互、无人值守安装
可选软件版本
docker官方仓库
nginx=1.17 / 1.16
mysql=8 / 5.7 / 5.6
nodejs=12 / 10 / 8
php=7.4 / 7.3 / 7.2 / 7.1 / 5.6
mongodb=4 / 3
redis=5 / 4
安装步骤
本地安装git、docker和docker-compose(建议使用最新版本:1.23)。 附录1:docker安装
clone项目:
如果不是root
用户,那么将当前用户加入docker
用户组$ sudo gpasswd -a KaTeX parse error: Expected 'EOF', got '#' at position 14: {USER} docker#̲ 获取项目 git clone github.com/wallace5303/dnnmmp.git
构建并启动:
$ cd dnnmmp# 构建并运行(第一次安装建议使用此命令,方便查看打印的日志)$ docker-compose up# 后台运行$ docker-compose up -d
注意:Windows安装360安全卫士的同学,请先将其退出,不然安装过程中可能Docker创建账号过程可能被拦截,导致启动时文件共享失败;
查看生成的镜像:$ docker image ls
查看启动的容器:$ docker container ls
附录4:常见的问题
访问在浏览器中访问: localhost
常用命令
服务列表:redis|mysql|mongodb|nginx|php# 列出 Compose 文件中包含的镜像$ docker-compose images# 创建所有服务并启动$ docker-compose up$ docker-compose up -d # 全部后台启动# 创建单个服务$ docker-compose up redis$ docker-compose up -d redis # 后台启动# 如果容器已经创建# 启动$ docker-compose start redis# 停止$ docker-compose stop redis# 重启$ docker-compose restart redis# 重新构建$ docker-compose build redis# 删除$ docker-compose rm redis
阿里云
网易云
时速云
DaoCloud
Docker Hub
Quay
https://registry.docker-cn.com
http://hub-mirror.c.163.com
https://3laho3y3.mirror.aliyuncs.com
http://f1361db2.m.daocloud.io
https://mirror.ccs.tencentyun.com
mkdir -p /etc/docker
sudo tee /etc/docker/daemon.json <<-'EOF'
{
"registry-mirrors": ["" ]
}
该脚本可以将 --registry-mirror 加入到你的 Docker 配置文件 /etc/docker/daemon.json 中。适用于 Ubuntu14.04、Debian、CentOS6 、CentOS7、Fedora、Arch Linux、openSUSE Leap 42.1,其他版本可能有细微不同。更多详情请访问文档。
curl -sSL https://raw.githubusercontent.com/wss434631143/xiaoshujiang/master/articles/Docker/shell/set_mirror.sh | sh -s <your accelerate address>
# 直接修改 /usr/lib/systemd/system/docker.service 启动脚本
vim /usr/lib/systemd/system/docker.service
# 在dockerd后面加参数
ExecStart=/usr/bin/dockerd --registry-mirror=<your accelerate address>
以上操作后重启一下 Docker
sudo systemctl daemon-reload
sudo systemctl restart docker
国内 docker 仓库镜像对比
https://ieevee.com/tech/2016/09/28/docker-mirror.html
查找最快的docker镜像
https://github.com/silenceshell/docker_mirror
Docker - 配置国内加速器加速镜像下载。 - TonyZhang24 - 博客园
https://www.cnblogs.com/atuotuo/p/6264800.html
DaoCloud – 企业级云计算领域的创新领导者
https://www.daocloud.io/mirror#accelerator-doc
tee命令_Linux tee 命令用法详解:把数据重定向到给定文件和屏幕上
http://man.linuxde.net/tee
为了方便修改将上面的两个文件复制出来挂载在宿主机上,宿主机和容器之间的复制命令为
docker cp host_path containerID:container_path --从主机复制到容器
docker cp containerID:container_path host_path --从容器复制到主机
解决办法
$ docker ps
$ ps -aux | grep -v grep | grep docker-proxy
停止 doker 进程,删除所有容器,然后删除 local-kv.db 这个文件,再启动 docker 就可以了。
$ sudo service docker stop
$ docker rm $(docker ps -aq)
$ sudo rm /var/lib/docker/network/files/local-kv.db
$ sudo service docker start
docker命令报错
Error response from daemon: network bridge_default has active endpoints
Error: network bridge_default has active endpoints
Error response from daemon: network bridge_default has active endpoints
这个错误在于docker-compose默认会创建一个网络 bridge_default ,并将相关的容器添加到此网络中。意思是 默认网络 bridge_default 有一个活动端点 所以该网络不能执行删除操作
ERROR: network bridge_default has active endpoints
有一个默认网络端点在活动所以无法执行 docker-compose down操作
解决方法是先强制删除该网络下的所有容器
docker rm -f CONTAINERID 强制停止删除容器
然后查看执行查看docker网络命令查看默认网络的详细信息中有哪些容器在活动
docker network ls //查看docker网络列表
docker network inspect NETWORKID //查看该网络的详细信息
执行强制停止容器的网络端点命令
docker network disconnect -f NEWWORKNAME CONTAINERNAME //强制清除该网络中某个容器的endpoint -f可不加
例如
docker network disconnect -f bridge_default mysql
最后可以删除docker中network
docker network rm bridge_default