Saltar al contenido

¿Cómo verificar si el contenido de dos imágenes de Docker es exactamente el mismo?

Esta cuestión se puede tratar de diversas maneras, pero nosotros te dejamos la que en nuestra opinión es la solución más completa.

Solución:

Si desea comparar el contenido de las imágenes, puede utilizar docker inspect comando y puede mirar la sección RootFS

docker inspect redis

    "RootFS": 
        "Type": "layers",
        "Layers": [
            "sha256:eda7136a91b7b4ba57aee64509b42bda59e630afcb2b63482d1b3341bf6e2bbb",
            "sha256:c4c228cb4e20c84a0e268dda4ba36eea3c3b1e34c239126b6ee63de430720635",
            "sha256:e7ec07c2297f9507eeaccc02b0148dae0a3a473adec4ab8ec1cbaacde62928d9",
            "sha256:38e87cc81b6bed0c57f650d88ed8939aa71140b289a183ae158f1fa8e0de3ca8",
            "sha256:d0f537e75fa6bdad0df5f844c7854dc8f6631ff292eb53dc41e897bc453c3f11",
            "sha256:28caa9731d5da4265bad76fc67e6be12dfb2f5598c95a0c0d284a9a2443932bc"
        ]
    

si todas las capas son idénticas, las imágenes tienen contenido idéntico

Después de investigar un poco, se me ocurrió una solución que es rápida y limpia según mis pruebas.

La solución general es esta:

  1. Crea un contenedor para tu imagen a través de docker create ...
  2. Exporte todo su sistema de archivos a un archivo tar a través de docker export ...
  3. Canalice los nombres de directorio de archivo, nombres de enlace simbólico, contenido de enlace simbólico, nombres de archivo y contenido de archivo, a una función hash (por ejemplo, MD5)
  4. Compare los hashes de diferentes imágenes para verificar si sus contenidos son iguales o no

Y eso es.

Técnicamente, esto se puede hacer de la siguiente manera:

1) Crear archivo md5docker, y darle derechos de ejecución, por ejemplo, chmod +x md5docker:

#!/bin/sh
dir=$(dirname "$0")
docker create $1 |  md5; docker rm $cid > /dev/null; 

2) Crear archivo tarcat, y darle derechos de ejecución, por ejemplo, chmod +x tarcat:

#! / usr / bin / env python3 # coding = utf-8 if __name__ == '__main__': import sys import tarfile con tarfile.open (fileobj = sys.stdin.buffer, mode = "r | *") como tar : para tarinfo en tar: si tarinfo.isfile (): print (tarinfo.name, flush = True) con tar.extractfile (tarinfo) como archivo: sys.stdout.buffer.write (file.read ()) elif tarinfo. isdir (): print (tarinfo.name, flush = True) elif tarinfo.issym () o tarinfo.islnk (): print (tarinfo.name, flush = True) print (tarinfo.linkname, flush = True) else: print (" 33[0;31mIGNORING:33[0m ", tarinfo.name, file=sys.stderr)

3) Now invoke ./md5docker , where is your image name or id, to compute an MD5 hash of the entire file system of your image.

To verify if two images have the same contents just check that their hashes are equal as computed in step 3).

Note that this solution only considers as content directory structure, regular file contents, and symlinks (soft and hard). If you need more just change the tarcat script by adding more elif clauses testing for the content you wish to include (see Python’s tarfile, and look for methods TarInfo.isXXX() corresponding to the needed content).

The only limitation I see in this solution is its dependency on Python (I am using Python3, but it should be very easy to adapt to Python2). A better solution without any dependency, and probably faster (hey, this is already very fast), is to write the tarcat script in a language supporting static linking so that a standalone executable file was enough (i.e., one not requiring any external dependencies, but the sole OS). I leave this as a future exercise in C, Rust, OCaml, Haskell, you choose.

Note, if MD5 does not suit your needs, just replace md5 inside the first script with your hash utility.

Hope this helps anyone reading.

There doesn’t seem to be a standard way for doing this. The best way that I can think of is using the Docker multistage build feature.
For example, here I am comparing the apline and debian images. In yourm case set the image names to the ones you want to compare

I basically copy all the file from each image into a git repository and commit after each copy.

FROM alpine as image1

FROM debian as image2

FROM ubuntu
RUN apt-get update && apt-get install -y git
RUN git config --global user.email "[email protected]e.com "&&  git config --global user.name" Su nombre "EJECUTAR mkdir imágenes WORKDIR imágenes EJECUTAR git init COPY --from = image1 /. EJECUTAR git add. && git commit -m" image1 "COPY --from = image2 /. EJECUTAR git add. && git commit -m "image2" CMD tail> / dev /null

Esto le dará una imagen con un repositorio de git que registra las diferencias entre las dos imágenes.

docker build -t compare .
docker run -it compare bash

Ahora si haces un git log puedes ver los registros y puedes comparar las dos confirmaciones usando git diff

Nota: Si la creación de la imagen falla en la segunda confirmación, esto significa que las imágenes son idénticas, ya que una confirmación de git fallará si no hay cambios para confirmar.

Calificaciones y reseñas

¡Haz clic para puntuar esta entrada!
(Votos: 0 Promedio: 0)



Utiliza Nuestro Buscador

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *