Search code examples
dockerdockerfile

How to run docker commands using a docker file


I've certain basic docker command which i run in my terminal. Now what i want is to use all the basic docker commands into one docker file and then, build that docker file.

For eg. Consider two docker files File - Docker1, Docker2

Docker1 contains list of commands to run

And inside Docker2 i want to build Docker1 and run it as well

Docker2:(Consider the scenario with demo code)

FROM ubuntu:16.04
MAINTAINER [email protected]
WORKDIR /home/docker_test/
RUN docker build -t Docker1 .
RUN docker run -it Docker1

I want to do something like this. But it is throwing - docker: error response from daemon oci runtime create failed container_linux.go

How can I do this? Where am I going wrong

P.S - I'm new to Docker


Solution

  • Your example is mixing two steps, image creation and running an image, that can't be mixed that way (with a Dockerfile).

    Image creation

    A `Dockerfile`is used to create an image. Let's take this [alpine3.8 docker file][1] as a minimal example
    FROM scratch
    ADD rootfs.tar.xz /
    CMD ["/bin/sh"]
    

    It's a base image, it's not based on another image, it starts FROM scratch. Then a tar file is copied and unpacked, see ADD and the shell is set as starting command, see CMD. You can build this with

    docker build -t test_image .
    

    Issued from the same folder, where the Dockerfile is. You will also need the rootfs.tar.xz in that folder, copy it from the alpine link above.

    Running a container

    From that test_image you can now spawn a container with

    docker run -it test_image
    

    It will start up and give you the shell inside the container.

    Docker Compose

    Usually there is no need to build your images over and over again before spawning a new container. But if you really need to, you can do it with docker-compose. Docker Compose is intended to define and run a service stack consisting of several containers. The stack is defined in a docker-compose.yml file.

    version: '3'
    services:
      alpine_test:
        build: .
    

    build: . takes care of building the image again before starting up, but usually it is sufficient to have just image: <image_name> and use an already existing image.