Panduan Docker untuk Java

1. Ikhtisar

Pada artikel ini, kita melihat API khusus platform mapan lainnya - Klien API Java untuk Docker .

Sepanjang artikel ini, kami memahami cara bagaimana terhubung dengan daemon Docker yang sedang berjalan dan jenis fungsionalitas penting apa yang ditawarkan API kepada pengembang Java.

2. Ketergantungan Maven

Pertama, kita perlu menambahkan ketergantungan utama ke file pom.xml kita :

 com.github.docker-java docker-java 3.0.14 

Pada saat penulisan artikel ini, versi terbaru dari API adalah 3.0.14 . Setiap rilis dapat dilihat dari halaman rilis GitHub atau dari repositori Maven.

3. Menggunakan Klien Docker

DockerClient adalah tempat kita dapat membuat koneksi antara mesin Docker / daemon dan aplikasi kita.

Secara default, daemon Docker hanya dapat diakses di file unix: ///var/run/docker.sock . Kami dapat berkomunikasi secara lokal dengan mesin Docker yang mendengarkan di soket Unix kecuali dikonfigurasi sebaliknya .

Di sini, kami menerapkan kelas DockerClientBuilder untuk membuat koneksi dengan menerima pengaturan default:

DockerClient dockerClient = DockerClientBuilder.getInstance().build();

Demikian pula, kita dapat membuka koneksi dalam dua langkah:

DefaultDockerClientConfig.Builder config = DefaultDockerClientConfig.createDefaultConfigBuilder(); DockerClient dockerClient = DockerClientBuilder .getInstance(config) .build();

Karena mesin dapat mengandalkan karakteristik lain, klien juga dapat dikonfigurasi dengan kondisi berbeda.

Misalnya, pembangun menerima URL server, yaitu, kita dapat memperbarui nilai koneksi jika mesin tersedia pada port 2375 :

DockerClient dockerClient = DockerClientBuilder.getInstance("tcp://docker.baeldung.com:2375").build();

Perhatikan bahwa kita perlu menambahkan string koneksi dengan unix: // atau tcp: // tergantung pada jenis koneksi.

Jika kita melangkah lebih jauh, kita dapat berakhir dengan konfigurasi yang lebih maju menggunakan kelas DefaultDockerClientConfig :

DefaultDockerClientConfig config = DefaultDockerClientConfig.createDefaultConfigBuilder() .withRegistryEmail("[email protected]") .withRegistryPassword("baeldung") .withRegistryUsername("baeldung") .withDockerCertPath("/home/baeldung/.docker/certs") .withDockerConfig("/home/baeldung/.docker/") .withDockerTlsVerify("1") .withDockerHost("tcp://docker.baeldung.com:2376").build(); DockerClient dockerClient = DockerClientBuilder.getInstance(config).build();

Demikian juga, kita dapat melakukan pendekatan yang sama menggunakan Properties :

Properties properties = new Properties(); properties.setProperty("registry.email", "[email protected]"); properties.setProperty("registry.password", "baeldung"); properties.setProperty("registry.username", "baaldung"); properties.setProperty("DOCKER_CERT_PATH", "/home/baeldung/.docker/certs"); properties.setProperty("DOCKER_CONFIG", "/home/baeldung/.docker/"); properties.setProperty("DOCKER_TLS_VERIFY", "1"); properties.setProperty("DOCKER_HOST", "tcp://docker.baeldung.com:2376"); DefaultDockerClientConfig config = DefaultDockerClientConfig.createDefaultConfigBuilder() .withProperties(properties).build(); DockerClient dockerClient = DockerClientBuilder.getInstance(config).build();

Pilihan lain kecuali kita mengonfigurasi pengaturan mesin di kode sumber adalah mengatur variabel lingkungan yang sesuai sehingga kita hanya dapat mempertimbangkan instantiasi default DockerClient dalam proyek:

export DOCKER_CERT_PATH=/home/baeldung/.docker/certs export DOCKER_CONFIG=/home/baeldung/.docker/ export DOCKER_TLS_VERIFY=1 export DOCKER_HOST=tcp://docker.baeldung.com:2376

4. Manajemen Kontainer

API memungkinkan kita untuk memiliki berbagai pilihan tentang manajemen kontainer. Mari kita lihat satu per satu.

4.1. Daftar Penampung

Sekarang setelah kita memiliki koneksi yang mapan, kita dapat membuat daftar semua container yang sedang berjalan yang terletak di host Docker:

List containers = dockerClient.listContainersCmd().exec();

Asalkan menampilkan container yang sedang berjalan tidak sesuai dengan kebutuhan, kita dapat menggunakan opsi yang ditawarkan untuk query container.

Dalam kasus ini, kami menampilkan penampung dengan status "keluar":

List containers = dockerClient.listContainersCmd() .withShowSize(true) .withShowAll(true) .withStatusFilter("exited").exec()

Ini setara dengan:

$ docker ps -a -s -f status=exited # or $ docker container ls -a -s -f status=exited

4.2. Buat Penampung

Pembuatan container disajikan dengan metode createContainerCmd . Kita bisa mendeklarasikan deklarasi yang lebih kompleks menggunakan metode yang tersedia yang dimulai dengan awalan "with" .

Mari kita asumsikan bahwa kita memiliki perintah pembuatan buruh pelabuhan yang mendefinisikan kontainer MongoDB yang bergantung pada host yang mendengarkan secara internal pada port 27017:

$ docker create --name mongo \ --hostname=baeldung \ -e MONGO_LATEST_VERSION=3.6 \ -p 9999:27017 \ -v /Users/baeldung/mongo/data/db:/data/db \ mongo:3.6 --bind_ip_all

We're able to bootstrap the same container along with its configurations programmatically:

CreateContainerResponse container = dockerClient.createContainerCmd("mongo:3.6") .withCmd("--bind_ip_all") .withName("mongo") .withHostName("baeldung") .withEnv("MONGO_LATEST_VERSION=3.6") .withPortBindings(PortBinding.parse("9999:27017")) .withBinds(Bind.parse("/Users/baeldung/mongo/data/db:/data/db")).exec();

4.3. Start, Stop, and Kill a Container

Once we create the container, we can start, stop and kill it by name or id respectively:

dockerClient.startContainerCmd(container.getId()).exec(); dockerClient.stopContainerCmd(container.getId()).exec(); dockerClient.killContainerCmd(container.getId()).exec();

4.4. Inspect a Container

The inspectContainerCmd method takes a String argument which indicates the name or id of a container. Using this method, we can observe the metadata of a container directly:

InspectContainerResponse container = dockerClient.inspectContainerCmd(container.getId()).exec();

4.5. Snapshot a Container

Similar to the docker commit command, we can create a new image using the commitCmd method.

In our example, the scenario is, we previously run an alpine:3.6 container whose id is “3464bb547f88” and installed git on top of it.

Now, we want to create a new image snapshot from the container:

String snapshotId = dockerClient.commitCmd("3464bb547f88") .withAuthor("Baeldung <[email protected]>") .withEnv("SNAPSHOT_YEAR=2018") .withMessage("add git support") .withCmd("git", "version") .withRepository("alpine") .withTag("3.6.git").exec();

Since our new image bundled with git remains on the host, we can search it on the Docker host:

$ docker image ls alpine --format "table {{.Repository}} {{.Tag}}" REPOSITORY TAG alpine 3.6.git

5. Image Management

There are a few applicable commands we are given to manage image operations.

5.1. List Images

To list all the available images including dangling images on the Docker host, we need to apply to the listImagesCmd method:

List images = dockerClient.listImagesCmd().exec();

If we have two images on our Docker Host, we should obtain the Image objects of them at run-time. The images we look for are:

$ docker image ls --format "table {{.Repository}} {{.Tag}}" REPOSITORY TAG alpine 3.6 mongo 3.6

Next to this, to see the intermediate images, we need to request it explicitly:

List images = dockerClient.listImagesCmd() .withShowAll(true).exec();

If only displaying the dangling images is the case, the withDanglingFilter method must be considered:

List images = dockerClient.listImagesCmd() .withDanglingFilter(true).exec();

5.2. Build an Image

Let's focus on the way of building an image using the API. The buildImageCmd method builds Docker images from a Dockerfile. In our project, we already have one Dockerfile which gives an Alpine image with git installed:

FROM alpine:3.6 RUN apk --update add git openssh && \ rm -rf /var/lib/apt/lists/* && \ rm /var/cache/apk/* ENTRYPOINT ["git"] CMD ["--help"]

The new image will be built without using cache and before starting the building process, in any case, Docker engine will attempt to pull the newer version of alpine:3.6. If everything goes well, we should eventually see the image with the given name,alpine:git:

String imageId = dockerClient.buildImageCmd() .withDockerfile(new File("path/to/Dockerfile")) .withPull(true) .withNoCache(true) .withTag("alpine:git") .exec(new BuildImageResultCallback()) .awaitImageId();

5.3. Inspect an Image

We can inspect the low-level information about an image thanks to the inspectImageCmd method:

InspectImageResponse image = dockerClient.inspectImageCmd("161714540c41").exec();

5.4. Tag an Image

Adding a tag to our image is quite simple using the dockertag command, so the API is no exception. We can carry out the same intention with the tagImageCmd method as well. To tag a Docker image with id 161714540c41 into the baeldung/alpine repository with git:

String imageId = "161714540c41"; String repository = "baeldung/alpine"; String tag = "git"; dockerClient.tagImageCmd(imageId, repository, tag).exec();

We would list the newly created image, and there it is:

$ docker image ls --format "table {{.Repository}} {{.Tag}}" REPOSITORY TAG baeldung/alpine git

5.5. Push an Image

Before sending out an image to a registry service, the docker client must be configured to cooperate with the service because working with registries need to be authenticated in advance.

Since we assume that the client was configured with Docker Hub, we can push the baeldung/alpine image to the baeldung DockerHub account:

dockerClient.pushImageCmd("baeldung/alpine") .withTag("git") .exec(new PushImageResultCallback()) .awaitCompletion(90, TimeUnit.SECONDS);

We must abide by the duration of the process. In the example, we are waiting 90 seconds.

5.6. Pull an Image

To download images from registry services, we make use of the pullImageCmd method. In addition, if the image being pulled from a private registry, the client must know our credential otherwise the process ends up with a failure. Same as the pulling an image, we specify a callback along with a fixed period to pull an image:

dockerClient.pullImageCmd("baeldung/alpine") .withTag("git") .exec(new PullImageResultCallback()) .awaitCompletion(30, TimeUnit.SECONDS);

To check out whether the mentioned image exists on the Docker host after pulling it:

$ docker images baeldung/alpine --format "table {{.Repository}} {{.Tag}}" REPOSITORY TAG baeldung/alpine git

5.7. Remove an Image

Another simple function among the rest is the removeImageCmd method. We can remove an image with its short or long ID:

dockerClient.removeImageCmd("beaccc8687ae").exec();

5.8. Search in Registry

To search an image from Docker Hub, the client comes with the searchImagesCmd method taking a String value which indicates a term. Here, we explore images related to a name containing ‘Java' in Docker Hub:

List items = dockerClient.searchImagesCmd("Java").exec();

The output returns first 25 related images in a list of SearchItem objects.

6. Volume Management

If Java projects need to interact with Docker for volumes, we should also take into account this section. Briefly, we look at the fundamental techniques of volumes provided by the Docker Java API.

6.1. List Volumes

All of the available volumes including named and unnamed are listed with:

ListVolumesResponse volumesResponse = dockerClient.listVolumesCmd().exec(); List volumes = volumesResponse.getVolumes();

6.2. Inspect a Volume

The inspectVolumeCmd method is the form to show the detailed information of a volume. We inspect the volume by specifying its short id:

InspectVolumeResponse volume = dockerClient.inspectVolumeCmd("0220b87330af5").exec();

6.3. Create a Volume

The API serves two different options to create a volume. The non-arg createVolumeCmd method creates a volume where the name is given by Docker:

CreateVolumeResponse unnamedVolume = dockerClient.createVolumeCmd().exec();

Rather than using the default behavior, the helper method called withName lets us set a name to a volume:

CreateVolumeResponse namedVolume = dockerClient.createVolumeCmd().withName("myNamedVolume").exec();

6.4. Remove a Volume

We can intuitively delete a volume from the Docker host using the removeVolumeCmd method. What is important to note that we cannot delete a volume if it is in use from a container. We remove the volume, myNamedVolume, from the volume list:

dockerClient.removeVolumeCmd("myNamedVolume").exec();

7. Network Management

Our last section is about managing network tasks with the API.

7.1. List Networks

We can display the list of network units with one of the conventional API methods starting with list:

List networks = dockerClient.listNetworksCmd().exec();

7.2. Create a Network

The equivalent of the docker network create command is conducted with the createNetworkCmd method. If we have a thirty party or a custom network driver, the withDriver method can accept them besides the built-in drivers. In our case, let's create a bridge network whose name is baeldung:

CreateNetworkResponse networkResponse = dockerClient.createNetworkCmd() .withName("baeldung") .withDriver("bridge").exec();

Furthermore, creating a network unit with the default settings doesn't solve the problem, we can apply for other helper methods to construct an advanced network. Thus, to override the default subnetwork with a custom value:

CreateNetworkResponse networkResponse = dockerClient.createNetworkCmd() .withName("baeldung") .withIpam(new Ipam() .withConfig(new Config() .withSubnet("172.36.0.0/16") .withIpRange("172.36.5.0/24"))) .withDriver("bridge").exec();

The same command we can run with the docker command is:

$ docker network create \ --subnet=172.36.0.0/16 \ --ip-range=172.36.5.0/24 \ baeldung

7.3. Inspect a Network

Displaying the low-level details of a network is also covered in the API:

Network network = dockerClient.inspectNetworkCmd().withNetworkId("baeldung").exec();

7.4. Remove a Network

We can safely remove a network unit with its name or id using the removeNetworkCmd method:

dockerClient.removeNetworkCmd("baeldung").exec();

8. Conclusion

In this extensive tutorial, we explored the various diverse functionality of the Java Docker API Client, along with several implementation approaches for deployment and management scenarios.

Semua contoh yang diilustrasikan dalam artikel ini dapat ditemukan di GitHub.