Docker error response from daemon no command specified

I am trying to take a docker container from one machine and run it on another and encountering this error: "Error response from daemon: No command specified". Below is a simplified example showing...

I am trying to take a docker container from one machine and run it on another and encountering this error: «Error response from daemon: No command specified«.

Below is a simplified example showing the problem:

docker --version
Docker version 1.10.1, build 9e83765
docker pull ubuntu
docker run --name u1 -dit ubuntu:latest
docker export -o exported u1
docker stop u1
docker rm u1
docker import exported ubuntu:imported
docker run --name u1 -dit ubuntu:imported
docker: Error response from daemon: No command specified.

In that example, we first pull an image (ubuntu) and successfully create/run container u1 from it. Then we export that container to a file (exported), stop/remove the container, import the file into a new image (ubuntu:imported) and try to run a new container from it. It fails.

030's user avatar

030

5,80112 gold badges64 silver badges108 bronze badges

asked Feb 15, 2016 at 5:09

Greendrake's user avatar

0

docker export does not export everything about the container — just the filesystem. So, when importing the dump back into a new docker image, additional flags need to be specified to recreate the context.

For example, if the original container was running fine because the Dockerfile that was used for creating its image had CMD ["/usr/bin/supervisord"] in it, then import your dump this way:

docker import 
--change 'CMD ["/usr/bin/supervisord"]' 
path/to/dump.tar imagename:tagname

answered Aug 18, 2016 at 9:42

Greendrake's user avatar

GreendrakeGreendrake

1,2712 gold badges13 silver badges22 bronze badges

3

you can use docker load command to load images from archive file .
this command will import image file and args together.

answered May 17, 2018 at 2:58

Jian Pei's user avatar

Jian PeiJian Pei

2913 silver badges2 bronze badges

3

Got this error when trying to export and import docker microsoft/mssql-server-linux.

https://hub.docker.com/r/microsoft/mssql-server-linux/

Commands to export and import:

docker export --output "C:UsersoscarDesktopsqlTestMS.tar" msSQL

docker import "C:UsersoscarDesktopsqlTestMS.tar" mssql

However we could not find the command to run it. The solution was listing all containers on the exporting machine and looking at the command ran.

docker ps

enter image description here

From there we could find out how to run the correct command:

docker run --name msSQL -p 1401:1433 -d mssql:latest /opt/mssql/bin/sqlservr

answered Oct 12, 2018 at 11:32

Ogglas's user avatar

OgglasOgglas

3543 silver badges6 bronze badges

When you export a container it lost own history which contains image layers and meta data. So your container lost its pid states.

Every container should have a initial (root) process. You are overiding the default entrypoint on the dockerfile as bash. [edited] I think even you dont override it uses default , not defined in ubuntu base image. So you should start your initial process with cmd command. I think there is no bug. It is a dockerfile feature for reusablity.

answered Apr 11, 2016 at 21:11

pmoksuz's user avatar

2

Got it working with these additional steps:

  1. Create Dockerfile as follows:

    FROM ubuntu:imported
    ENTRYPOINT ["/bin/bash"]
    
  2. Build new image:

    docker build -t ubuntu:importedwithdockerfile .
    
  3. Now it will run:

    docker run --name u1 -dit ubuntu:importedwithdockerfile
    

However, it is still unclear why simply exported and then imported image does not work right away. Is this a bug?

if using import

docker save nginx:alpine | ssh rmeote-host docker import -
sha256:f6098fc18511abbbfe9e52ed0d0ccc1fbe4f7b018ee1cd85392999aa92ebba1b

# we see errors
docker container run -d -p 2020:80  nginx:alpine
docker: Error response from daemon: No command specified.
See 'docker run --help'.

if using load

docker save nginx:alpine | ssh remote-host "cat - | docker load"
Loaded image: nginx:alpine

docker container run --name nginx -dp 2020:80 nginx:alpine
7cc8836bef1e276f8aa986a09186e9e227542be3b094b082b9ab1f6d3c290a99
docker ps
CONTAINER ID   IMAGE          COMMAND                  CREATED         STATUS        PORTS                                   NAMES
7cc8836bef1e   nginx:alpine   "/docker-entrypoint.…"   2 seconds ago   Up 1 second   0.0.0.0:2020->80/tcp, :::2020->80/tcp   nginx

answered Jan 11, 2022 at 20:50

Shakiba Moshiri's user avatar

Starting from my last commit yesterday I am encountering with a strange problem where GitLab CI fails continuously with an error as shown below:

$ ssh -i $SSH_PRIVATE_KEY -o StrictHostKeyChecking=no $SERVER_USER@$SERVER_IP "docker run -d -p 8010:80 --name my_project $TAG_LATEST"
docker: Error response from daemon: No command specified.
See 'docker run --help'.
Cleaning up project directory and file based variables
ERROR: Job failed: exit code 125

This is an React App which should be build and deployed to my server.

This is my Dockerfile

FROM node:16.14.0-alpine as build

WORKDIR /app
COPY package*.json ./
RUN npm ci
COPY . .
RUN npm run build

FROM nginx:1.19-alpine

COPY --from=build /app/build /usr/share/nginx/html
RUN rm /etc/nginx/conf.d/default.conf
COPY nginx/nginx.conf /etc/nginx/conf.d
EXPOSE 80

CMD ["nginx", "-g", "daemon off;"]

In .gitlab-ci.yml file I have 2 stages build and deploy. For more clarity I would like to share it eaither:

stages:
  - build
  - deploy

variables:
  TAG_LATEST: $CI_REGISTRY_IMAGE/$CI_COMMIT_REF_NAME:latest
  DOCKER_DRIVER: overlay2
  DOCKER_TLS_CERTDIR: "/certs"

build_test:
  image: docker:latest
  stage: build
  services:
    - docker:19.03.0-dind
  script:
    - docker build -t $TAG_LATEST .
    - docker login -u gitlab-ci-token -p $CI_BUILD_TOKEN $CI_REGISTRY
    - docker push $TAG_LATEST
  environment:
    name: test
  rules:
    - if: $CI_COMMIT_BRANCH == "develop"
      when: on_success


deploy_test:
  image: alpine:latest
  stage: deploy
  only:
    - develop
  tags:
    - frontend
  script:
    - chmod og= $SSH_PRIVATE_KEY
    - apk update && apk add openssh-client
    - ssh -i $SSH_PRIVATE_KEY -o StrictHostKeyChecking=no $SERVER_USER@$SERVER_IP "docker login -u gitlab-ci-token -p $CI_BUILD_TOKEN $CI_REGISTRY"
    - ssh -i $SSH_PRIVATE_KEY -o StrictHostKeyChecking=no $SERVER_USER@$SERVER_IP "docker pull $TAG_LATEST"
    - ssh -i $SSH_PRIVATE_KEY -o StrictHostKeyChecking=no $SERVER_USER@$SERVER_IP "docker container rm -f my_project || true"
    - ssh -i $SSH_PRIVATE_KEY -o StrictHostKeyChecking=no $SERVER_USER@$SERVER_IP "docker run -d -p 8010:80 --name my_project $TAG_LATEST"
  environment:
    name: test

I did the following steps:

1st tried to run image using docker run command manually in my server. The result was the same!

2nd I pulled project from gitlab to the brand new folder and run first docker build -my_project . command then as I did it in server. It worked on my local machine.

3rd I re-verified my code base with ChatGPT and it found no error.

Hi @krmao,

The fundamental issue is that the image doesn’t specify a command (container entrypoint, which is a command to launch some process) to run.

$ docker inspect krmao/spingcloud-discovery-eureka-server | grep Entrypoint
            "Entrypoint": null,
            "Entrypoint": null,

Note that the base image on Docker Hub (java:8) doesn’t specify it either.

$ docker inspect java:8 | grep Entrypoint
            "Entrypoint": null,
            "Entrypoint": null,

In your case, Jib is simply inheriting the entrypoint of java:8, because your eureka-server project is configured as a WAR project. A WAR is to be deployed to an application server or a Servlet engine (such as Tomcat and Jetty). Obviously, java:8 is just a JDK image and doesn’t have such an engine.

You could use a Jetty or Tomcat base image and configure Jib properly according to their server requirements, but since this is a Spring Boot app, I highly recommend moving away from WAR. Spring Boot apps already embed a Servlet engine. I was able to make this work with the following changes by not applying the WAR plugin. (Note this is part of the whole changes, and you’ll need to apply the WAR Plugin in other sub-projects to build them successfully. However, I highly recommend migrating from WAR for those projects as well.)

diff --git a/service/springcloud/build.gradle b/service/springcloud/build.gradle
index 74d9a6c2..6288a32b 100644
--- a/service/springcloud/build.gradle
+++ b/service/springcloud/build.gradle
@@ -52,7 +52,6 @@ subprojects {
     apply plugin: 'kotlin-spring'
     apply plugin: 'java'
     apply plugin: 'eclipse'
-    apply plugin: 'war'
     apply plugin: 'org.springframework.boot'
     apply plugin: 'io.spring.dependency-management'
     sourceCompatibility = JavaVersion.VERSION_1_8
diff --git a/service/springcloud/components/springcloud-discovery/eureka-server/build.gradle b/service/springcloud/components/springcloud-discovery/eureka-server/build.gradle
index c008e08e..79fee6fd 100644
--- a/service/springcloud/components/springcloud-discovery/eureka-server/build.gradle
+++ b/service/springcloud/components/springcloud-discovery/eureka-server/build.gradle
@@ -1,6 +1,6 @@
 def finalName= 'spingcloud-discovery-eureka-server'
 def finalPort = "5388"
-def finalMainClass = 'com.smart.springcloud.discovery.eurekaserver.EurekaServerApplication'
+//def finalMainClass = 'com.smart.springcloud.discovery.eurekaserver.EurekaServerApplicationKt'
 
 // 参考文档 https://www.cnblogs.com/edisonchou/p/springboot_on_docker_foundation.html
 // 参考文档 https://spring.io/guides/gs/spring-boot-docker/
@@ -25,8 +25,6 @@ jib {
     container {
         creationTime = 'USE_CURRENT_TIMESTAMP'
         jvmFlags = ['-Xms512m', '-Xdebug', '-Dfile.encoding=utf-8', '-Duser.timezone=Asia/Shanghai']
-        mainClass = finalMainClass
-        args = []
         ports = [finalPort]
     }
     dockerClient {
@@ -34,10 +32,6 @@ jib {
     }
 }
 
-war {
-    archiveName "${finalName}.war"
-}
-
 dependencies {
     implementation("org.springframework.cloud:spring-cloud-starter-netflix-eureka-server")
 }

See the output:

$ ./gradlew eureka-server:clean                                  
...
BUILD SUCCESSFUL in 478ms
1 actionable task: 1 executed
$ ./gradlew -Djib.to.image=foo -Djib.dockerClient.executable=$(which docker) eureka-server:jibDockerBuild
...
> Task :eureka-server:jibDockerBuild
...
Container entrypoint set to [java, -Xms512m, -Xdebug, -Dfile.encoding=utf-8, -Duser.timezone=Asia/Shanghai, -cp, /app/resources:/app/classes:/app/libs/*, com.smart.springcloud.discovery.eurekaserver.EurekaServerApplicationKt]

Built image to Docker daemon as foo, foo:0.0.1, foo
...
BUILD SUCCESSFUL in 6s
3 actionable tasks: 3 executed
$ docker run --rm -p5388:5388 foo
SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder".
SLF4J: Defaulting to no-operation (NOP) logger implementation
SLF4J: See http://www.slf4j.org/codes.html#StaticLoggerBinder for further details.

  .   ____          _            __ _ _
 /\ / ___'_ __ _ _(_)_ __  __ _    
( ( )___ | '_ | '_| | '_ / _` |    
 \/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |___, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::        (v2.3.3.RELEASE)

Nov 12, 2020 6:54:11 AM org.apache.catalina.core.StandardService startInternal
INFO: Starting service [Tomcat]
Nov 12, 2020 6:54:11 AM org.apache.catalina.core.StandardEngine startInternal
INFO: Starting Servlet engine: [Apache Tomcat/9.0.37]
Nov 12, 2020 6:54:11 AM org.apache.catalina.core.ApplicationContext log
INFO: Initializing Spring embedded WebApplicationContext
Nov 12, 2020 6:54:12 AM com.sun.jersey.server.impl.application.WebApplicationImpl _initiate
INFO: Initiating Jersey application, version 'Jersey: 1.19.1 03/11/2016 02:08 PM'

Then from another terminal,

$ curl localhost:5388
<!doctype html>
<!--[if lt IE 7]>      <html class="no-js lt-ie9 lt-ie8 lt-ie7"> <![endif]-->
<!--[if IE 7]>         <html class="no-js lt-ie9 lt-ie8"> <![endif]-->
<!--[if IE 8]>         <html class="no-js lt-ie9"> <![endif]-->
<!--[if gt IE 8]><!--> <html class="no-js"> <!--<![endif]-->
  <head>
    <base href="/">

Some minor notes:

  1. You don’t need to set jib.container.mainClass, since Jib can infer the only main class. However, if you do want to set it, it should be ....EurekaServerApplicationKt and not ....EurekaServerApplication. (This is the actual Java class for the corresponding Kotlin code.)
  2. No need to repeat latest in jib.to.tags. jib.to.tags actually mean additional tags. docker.io/krmao/... in jib.to.image already implies docker.io/krmao/...:latest.
             image = "docker.io/krmao/${finalName}"  // 上传后在 https://hub.docker.com/repositories 中查看
    -        tags = ['0.0.1', 'latest']
    +        tags = ['0.0.1']
             auth {

Содержание

  1. docker: Error response from daemon: No command specified. #2891
  2. Comments
  3. docker run fails with «Error response from daemon: No command specified» #4602
  4. Comments
  5. Footer
  6. After importing an image, run gives «no command specified» #1826
  7. Comments
  8. «Не указана команда» из повторно импортированного образа / контейнера докера
  9. Dockerfile
  10. Contents
  11. External
  12. Internal
  13. Overview
  14. Examples
  15. Syntax
  16. Example
  17. Variables
  18. Instructions
  19. COPY and Directory Handling
  20. ENTRYPOINT and CMD
  21. ENTRYPOINT
  22. ENTRYPOINT «exec» Form
  23. ENTRYPOINT «shell» Form
  24. CMD exec Form
  25. CMD Default Parameters to ENTRYPOINT Form
  26. CMD shell Form
  27. ENTRYPOINT and CMD Interaction
  28. RUN Shell Form
  29. RUN Exec Form
  30. WORKDIR
  31. MAINTAINER
  32. LABEL
  33. Recommended Format for Description Information
  34. VOLUME
  35. EXPOSE

docker: Error response from daemon: No command specified. #2891

Environment: macbook-pro

Description of the issue:
after gradle jib success and docker pull success and docker images can find success,
run the docker image error

Expected behavior:
run success and I can visit localhost:5388

Steps to reproduce:

  1. remote image is already exists
  2. git clone https://github.com/krmao/template/tree/master/service/springcloud/components/springcloud-discovery/eureka-server
  3. ./gradlew :eureka-server:jib
  4. docker pull krmao/spingcloud-discovery-eureka-server
  5. or just execute command ‘./gradlew :eureka-server:jibDockerBuild’ without step 3 and 4
  6. docker run -d —publish 5388:5388 —detach —name spingcloud-discovery-eureka-server krmao/spingcloud-discovery-eureka-server

jib-gradle-plugin Configuration:

Log output

Additional Information

  1. gradle bootRun is everything ok and can visit localhost:5388 on chrome
  2. local docker damon envirenment ok

The text was updated successfully, but these errors were encountered:

The fundamental issue is that the image doesn’t specify a command (container entrypoint, which is a command to launch some process) to run.

Note that the base image on Docker Hub ( java:8 ) doesn’t specify it either.

In your case, Jib is simply inheriting the entrypoint of java:8 , because your eureka-server project is configured as a WAR project. A WAR is to be deployed to an application server or a Servlet engine (such as Tomcat and Jetty). Obviously, java:8 is just a JDK image and doesn’t have such an engine.

You could use a Jetty or Tomcat base image and configure Jib properly according to their server requirements, but since this is a Spring Boot app, I highly recommend moving away from WAR. Spring Boot apps already embed a Servlet engine. I was able to make this work with the following changes by not applying the WAR plugin. (Note this is part of the whole changes, and you’ll need to apply the WAR Plugin in other sub-projects to build them successfully. However, I highly recommend migrating from WAR for those projects as well.)

Источник

docker run fails with «Error response from daemon: No command specified» #4602

Given the following block:

config.vm.provider «docker» do |d|
d.image = «centos:6»
end

and the following command:

vagrant up —provider=docker

I get the following error:

Error response from daemon: No command specified

Since the machine is down asking for logs through vagrant docker-logs crashes so I have no clue how to debug this.

The text was updated successfully, but these errors were encountered:

It looks like the centos:6 image expects a command. You’ll have to specify a d.command or d.run_command (off the top of my head I forget). See here: http://docs.vagrantup.com/v2/docker/configuration.html

EDIT: Looks like cmd is what you want.

Hi, makes sense. Thanks for looking into this. Guess that more helpful error reporting could prevent confusion in both instances:

Error response from deamon: No command specified. —> Please be aware that Docker expects at least one command that keeps running. In case you specify a command that does immediately return please change your configuration accordingly, see (URL) for further information.

And in case of running dokcer-logs not crashing but a message like: machine not running, unable to retrieve logs would be awesome.

© 2023 GitHub, Inc.

You can’t perform that action at this time.

You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session.

Источник

After importing an image, run gives «no command specified» #1826

After importing an image into docker on an AWS instance, I try to create a container with the run command, but get «no command specified. The same exact run command works with the image on another AWS instance before I export it. The output is shown below:

ubuntu@ip-10-171-57-34: $ cat coop-20130908.tar | sudo docker import — «tsg/cooperative»
2013/09/08 16:33:56 POST /v1.4/images/create?fromSrc=-&repo=tsg%2Fcooperative&tag=
9e83e8314572
ubuntu@ip-10-171-57-34: $ sudo docker run -d -p 24622:24622 -p 35146:35146 -p 50351:50351 -p 62250:62250 -p 8888:8888 -p 46246:46246 -p 22503:22503 «tsg/cooperative»
2013/09/08 16:34:57 POST /v1.4/containers/create
2013/09/08 16:34:57 Error: No command specified

The text was updated successfully, but these errors were encountered:

The command $ sudo docker run -d -p 24622:24622 -p 35146:35146 -p 50351:50351 -p 62250:62250 -p 8888:8888 -p 46246:46246 -p 22503:22503 «tsg/cooperative» doesn’t tell docker what command to be run.

An image imported via docker import won’t know what command to run. Any image will lose all of its associated metadata on export, so the default command won’t be available after importing it somewhere else.

The correct command would be something like: $ sudo docker run -d -p 24622:24622 -p 35146:35146 -p 50351:50351 -p 62250:62250 -p 8888:8888 -p 46246:46246 -p 22503:22503 tsg/cooperative /path/to/something.sh . Please note that I’ve also removed the double quotes around the image’s name, they’re not needed.

I will close this issue now as it’s not a real bug. Please feel free to comment if you have any questions.

On 09/08/2013 03:22 PM, unclejack wrote:

The command |$ sudo docker run -d -p 24622:24622 -p 35146:35146 -p
50351:50351 -p 62250:62250 -p 8888:8888 -p 46246:46246 -p 22503:22503
«tsg/cooperative»| doesn’t tell docker what command to be run.

An image imported via |docker import| won’t know what command to run.
Any image will lose all of its associated metadata on export, so the
default command won’t be available after importing it somewhere else.

The correct command would be something like: |$ sudo docker run -d -p
24622:24622 -p 35146:35146 -p 50351:50351 -p 62250:62250 -p 8888:8888
-p 46246:46246 -p 22503:22503 tsg/cooperative /path/to/something.sh|.
Please note that I’ve also removed the double quotes around the
image’s name, they’re not needed.

I will close this issue now as it’s not a real bug. Please feel free
to comment if you have any questions.


Reply to this email directly or view it on GitHub
#1826 (comment).

I verified that this command does run correctly against the image when
it is built, but not after it has been exportede, then imported
somewhere else.

Still not sure why I only getr this after export/import.

On 09/08/2013 03:22 PM, unclejack wrote:

The command |$ sudo docker run -d -p 24622:24622 -p 35146:35146 -p
50351:50351 -p 62250:62250 -p 8888:8888 -p 46246:46246 -p 22503:22503
«tsg/cooperative»| doesn’t tell docker what command to be run.

An image imported via |docker import| won’t know what command to run.
Any image will lose all of its associated metadata on export, so the
default command won’t be available after importing it somewhere else.

The correct command would be something like: |$ sudo docker run -d -p
24622:24622 -p 35146:35146 -p 50351:50351 -p 62250:62250 -p 8888:8888
-p 46246:46246 -p 22503:22503 tsg/cooperative /path/to/something.sh|.
Please note that I’ve also removed the double quotes around the
image’s name, they’re not needed.

I will close this issue now as it’s not a real bug. Please feel free
to comment if you have any questions.


Reply to this email directly or view it on GitHub
#1826 (comment).

I did notice that the image after import is significantly smaller than
the original image, leading me to believe that something adverse
happened during export or import. Didn’t get any error messages, though.

On 09/08/2013 04:08 PM, Bruce Johnson wrote:

I verified that this command does run correctly against the image when
it is built, but not after it has been exportede, then imported
somewhere else.

Still not sure why I only getr this after export/import.

On 09/08/2013 03:22 PM, unclejack wrote:

The command |$ sudo docker run -d -p 24622:24622 -p 35146:35146 -p
50351:50351 -p 62250:62250 -p 8888:8888 -p 46246:46246 -p 22503:22503
«tsg/cooperative»| doesn’t tell docker what command to be run.

An image imported via |docker import| won’t know what command to run.
Any image will lose all of its associated metadata on export, so the
default command won’t be available after importing it somewhere else.

The correct command would be something like: |$ sudo docker run -d -p
24622:24622 -p 35146:35146 -p 50351:50351 -p 62250:62250 -p 8888:8888
-p 46246:46246 -p 22503:22503 tsg/cooperative /path/to/something.sh|.
Please note that I’ve also removed the double quotes around the
image’s name, they’re not needed.

I will close this issue now as it’s not a real bug. Please feel free
to comment if you have any questions.


Reply to this email directly or view it on GitHub
#1826 (comment).

Источник

«Не указана команда» из повторно импортированного образа / контейнера докера

Я пытаюсь взять Docker-контейнер с одного компьютера и запустить его на другом, и обнаружил следующую ошибку: « Ошибка ответа от демона: команда не указана ».

Ниже приведен упрощенный пример, показывающий проблему:

В этом примере мы сначала извлекаем образ (ubuntu) и успешно создаем / запускаем u1 из него контейнер . Затем мы экспортируем этот контейнер в файл ( exported ), останавливаем / удаляем контейнер, импортируем файл в новое изображение ( ubuntu:imported ) и пытаемся запустить из него новый контейнер. Это не удается.

docker export не экспортирует все о контейнере — только файловая система. Таким образом, при импорте дампа обратно в новый образ докера необходимо указать дополнительные флаги для воссоздания контекста.

Например, если оригинальный контейнер работал нормально, потому что в нем содержался Dockerfile, который использовался для создания его образа CMD [«/usr/bin/supervisord»] , импортируйте свой дамп следующим образом:

Получил эту ошибку при попытке экспорта и импорта докер microsoft/mssql-server-linux .

Команды для экспорта и импорта:

Однако мы не смогли найти команду для его запуска. Решением было перечисление всех контейнеров на экспортирующем компьютере и просмотр команды run.

Оттуда мы могли бы узнать, как выполнить правильную команду:

При экспорте контейнера он теряет собственную историю, которая содержит слои изображения и метаданные. Таким образом, ваш контейнер потерял свои состояния pid.

Каждый контейнер должен иметь начальный (корневой) процесс. Вы пересекаете точку входа по умолчанию в файле Docker как bash. [отредактировано] Я думаю, что даже если вы не переопределите, он использует значение по умолчанию, не определенное в базовом образе Ubuntu. Итак, вы должны начать свой начальный процесс с помощью команды cmd. Я думаю, что нет ошибки. Это функция dockerfile для повторного использования.

Получил работу с этими дополнительными шагами:

Создайте Dockerfile следующим образом:

Создайте новый образ:

Теперь он будет работать:

Однако до сих пор неясно, почему просто экспортированное, а затем импортированное изображение не работает сразу. Это ошибка?

Вы можете использовать docker load команду для загрузки изображений из файла архива. эта команда импортирует файл изображения и аргументы вместе.

Источник

Dockerfile

Contents

External

Internal

Overview

A Dockerfile is a plain text file that defines how a container should look at build time. It contains all the steps that are required to create the image.

Each line in the Dockerfile generates a new layer in the image. Multiple commands can be combined on a single line, to reduce the number of layers.

The Dockerfile is used as the argument of the docker build command.

Examples

  • Dockerfile Example
  • A Dockerfile that builds a Centos-based image: https://github.com/NovaOrdis/playground/blob/master/docker/simplest-dockerfile/Dockerfile

Syntax

Example

Variables

Instructions

Instructions are also known as «directives», and they are part of a DSL.

A valid Dockerfile must start with a FROM instruction (ARG is the only instruction that can precede FROM). FROM specifies the base image upon which other layers are built. The identifier of the base image will appear as «Parent:» in the metadata of the resulting image.

If the only Dockerfile instruction is FROM, the build command simply downloads the base image into the local registry, listing the image’s repository and tag.

FROM can appear multiple times in a Dockerfile.

Defines a build-time variables. For more details on how build-time variables are defined and declared see:

The COPY instruction copies new files or directories from and adds them to the filesystem of the container at the path . T

he source paths are relative to the build context, but source paths that try to reach outside the context (for example ../something ) are considered invalid and will cause the build to fail.

If does not exist, it will be created. If the source file is a file, and does not have a trailing slash, the content of the source file will be copied in a file named dest . If has a trailing slash, the source file will be copied under the original name in a newly created directory dest .

Each occurrence of the COPY instruction creates a new layer in the final image.

This instruction is handled in a special manner relative to the build cache.

COPY should be preferred over ADD because it is more transparent.

To copy a file from the context, under the same name in the root of the image:

⚠️ If more than one source is listed, then the last argument must be a directory and end with a trailing slash «/».

If the file or directory already exists in the image and it is overwritten, it will take the new ownership.

COPY and Directory Handling

If the is a directory, its content will be recursively copied, but not the source directory itself. For example, if ./dir1 contains a file f.txt and a subdirectory ./dir2,

will create /opt/f.txt and /opt/dir2 in the image.

A trailing slash does not make a difference.

To copy the directory and its content, specify the same name as target:

Copies files from the local filesystem into the image.

This instruction is handled in a special manner relative to the build cache.

COPY should be preferred over ADD because it is more transparent.

ENTRYPOINT and CMD

ENTRYPOINT

The ENTRYPOINT instruction specifies the command and optionally the arguments to be used when a container is created from the image with docker run. ENTRYPOINT should be the preferred way of specifying the command to run when the container is intended to be used as executable, over the CMD instruction. ENTRYPOINT and CMD can be combined. For more details on the interaction between ENTRYPOINT and CMD, see ENTRYPOINT and CMD Interaction. If ENTRYPOINT is specified multiple times in the Dockerfile, only the last occurrence will be considered.

ENTRYPOINT has two forms: the exec form and the shell form.

ENTRYPOINT «exec» Form

The «exec» form involves specifying the entry point in JSON array format, with double-quoted («) arguments:

The docker run command line arguments, if any, are appended to the argument list specified in the «exec» form, overriding the arguments specified by CMD in «exec» form, if any. When the «exec» form is used, the executable specified as the first element runs with PID 1 in the container, and the signals are being sent directly to it. On the other hand, the shell pre-processing of the arguments does not happen, as no shell process is involved, as it is the case for the «shell» form, so arguments like «$HOME» are not expanded to the values available in the container environment.

ENTRYPOINT can be overridden on command line with:

The executable specification and its parameters propagates verbatim in the container metadata.

will propagate as:

ENTRYPOINT «shell» Form

In «shell» form, the executable and the arguments are specified as plain strings, not as a JSON array:

The «shell» form executes the arguments with «/bin/sh -c», and this becomes obvious inspecting the metadata representation:

⚠️ The shell form prevents any CMD or docker run command line arguments from being used: docker run arguments are not appended. When the shell form is used, the executable will not have the PID 1, and signals will not be passed to it, which means that it won’t be able to process SIGTERM sent by docker stop. However, the arguments are pre-processed by the shell, so arguments like $HOME are expanded with values present in the container’s environment.

To insure that signals will be passed to the executable, and the executable runs with PID 1, «exec» can be specified to precede the executable in the argument list:

The CMD instructions is intended to provide defaults for the executing container. The executable should be specified with ENTRYPOINT, and the default arguments with CMD. When ENTRYPOINT is missing, the executable can also be specified as part of the CMD instruction, as the first argument.

CMD exec Form

The «exec» form involves specifying the CMD arguments in double-quoted («) JSON array format:

The first argument should be an executable — if it is not, see «Default Parameters to ENTRYPOINT» below. The executable and the arguments are executed without any shell intervention. In consequence, shell pre-processing of the arguments does not happen, so arguments like «$HOME» are not expanded to the values available in the container environment. The executable passed as first argument gets PID 1, and signals are being sent directly to it.

If docker run is invoked with extra command line arguments, the execution will fail:

When CMD in «exec» format is used, the executable and arguments will propagate verbatim in the container metadata.

CMD Default Parameters to ENTRYPOINT Form

In this form, both CMD and ENTRYPOINT must be specified as JSON arrays:

In this situation, the CMD-specified arguments are overridden by command line arguments, if any. For the above configuration, executing the container without any argument will end up in the execution of:

and running the container with «-d» with end up in:

CMD shell Form

The «shell» form involves specifying arguments as unquoted strings:

The container will execute the CMD arguments with «/bin/sh -c», and this is obvious when inspecting the container metadata:

When using the «shell» form, the arguments are pre-processed by the shell, so arguments like $HOME are expanded with values present in the container’s environment.

ENTRYPOINT and CMD Interaction

Dockerfile should specify at least one of CMD or ENTRYPOINT commands. If there isn’t one, the executable launched when the container is run is specified by the last ancestor parent that has a ENTRYPOINT or a CMD specification — the value is inherited. If none of the ancestors specify an ENTRYPOINT/CMD and the current image does not specify one either, the Docker runtime produces this error message:

Conventionally, ENTRYPOINT in «exec» format should be used to set the executable and the default options, and CMD in «exec» format should be used to set the command-line overrridable options:

If there are no command-line overrides, ENTRYPOINT and CMD are combined. If there are command-line overrides, CMD options are dropped. When ENTRYPOINT and CMD are used together it’s important that the «exec» form is used with both instructions.

NO ENTRYPOINT ENTRYPOINT exec1 arg1 ENTRYPOINT [«exec1», «arg1»]
NO CMD inherited or error /bin/sh -c exec1 arg1 exec1 arg1
CMD [«exec2», «arg2»] exec2 arg2 /bin/sh -c exec1 arg1 exec1 arg1 exec2 arg2
CMD exec2 exec2 /bin/sh -c exec2 arg2 /bin/sh -c exec1 arg1 exec1 arg1 /bin/sh -c exec2 arg2

The USER instructions sets the user name or UID and optionally the user group or GID to use when running the image and for any RUN, CMD and ENTRYPOINT instructions that follow in Dockerfile.

The command will result in the insertion of a «User» element in the Config.User container metadata element:

which will instruct the container runtime to execute the root process with the specified UID and GID. The UID and GID specified as such can be overridden in the docker run command as follows:

If not specified, processes run as user «root» (UID 0). When the user doesn’t have a primary group then the image (or the next instructions) will be run with the root group.

When specifying a group for the user, the user will have only the specified group membership. Any other configured group memberships will be ignored.

The value of the USER directive is alphanumeric, representing a user name, the name must be resolvable in the container, otherwise the container won’t start:

The constraint does not apply to UIDs, a container will start with any UID.

Declares environment variable accessible to the processes in the container:

Environment variables declared this way can be used, and will be expanded in RUN commands in shell form.

The default values declared in the Dockerfile for a specific environment variable can be overridden on command line with:

Environment variables declared with the ENV statement can also be used in certain instructions as variables to be interpreted by the Dockerfile. Escapes are also handled for including variable-like syntax into a statement literally. The syntax that introduces variables in the Dockerfile is

The instructions that can use variables are:

The RUN instruction will execute any command in a new layer on top of the current image, and commit results. The resulted committed image will be used for the next step in the Dockerfile. Layering RUN instructions and generating commits conforms to the core concepts of Docker where commits are cheap and containers can be created from any point in an image’s history, much like source control. However, in practice, it is a good idea to reduce the number of RUN commands — and layers they generate.

It has two forms:

RUN Shell Form

The form performs shell command line expansion, so environment variables will be expanded to their values and used as such. Environment variables previously declared with ENV in the same Dockerfile will also be expanded. All shell command line expansion will take place. In shell form backslashes () can be used to continue a single RUN instruction onto the next line:example, consider these two lines:

A recommended pattern is to concatenate as many commands possible on a single logical line and separated them by ‘&&’, as shown:

RUN Exec Form

The exec from makes possible to run executables without relying on the existence of a shell binary in the image. It also does not perform shell command line expansion.

Running commands like yum in the Dockerfile is discouraged because it increases the time it takes for the build to finish. The alternative is to use base images that already have these updates applied.

WORKDIR

Changes the working directory within the context of the image being built, for the rest of the build instructions. If the WORKDIR doesn’t exist, it will be created. If a relative path is provided, it will be relative to the path of the previous WORKDIR instruction.

The WORKDIR instruction can resolve environment variables previously set using ENV.

MAINTAINER

It sets the «Author» field in the image metadata. It deprecated, use LABEL instead.

LABEL

Applies a label to the image.

Recommended Format for Description Information

VOLUME

The VOLUME instruction creates a mount point inside the container and marks it as holding an externally mounted data volume from the native host. If there is no such directory in the image, it will be created and left empty. The Docker documentation says that the docker run command initializes the newly created volume with any data that exists at the specified location in the base image. However, this only happens if no external volume is mounted. If an external volume is mounted, the content of the external volume will prevail. docker run must provide the Docker host-level directory and associate it with the mount point. At runtime, the storage driver will be bypassed when written data into the volume, so the I/O will be performed at native speeds.

The native host directory cannot be declared in Dockerfile: it is by its nature host-dependent and it presence cannot be guaranteed, so to preserve portability, the native host mount point must be specified when creating the container with docker run —mount or docker run -v. The actual location of the volume on the native host is a directory whose path is returned by the corresponding «Source» entry in output of:

EXPOSE

The ‘EXPOSE’ instruction serves as a hint (documentation) of the fact that the container listens on the specified ports at runtime, and those ports may be published. The instruction does not actually publish the port. Publishing is done with -p flag or -P flags in the docker run command.

Источник

The docker export container cannot be run after being imported. An error is reported: error response from daemon: no command specified

According to the error message, the command can be run without specifying the command

[[email protected] ~]# docker images
REPOSITORY          TAG                 IMAGE ID            CREATED             SIZE
docker.io/ubuntu    latest              fb52e22af1b0        3 weeks ago         72.8 MB

[[email protected] ~]# docker run -itd docker.io/ubuntu:latest
7ce403eba8d89127395e057eb4d6cf7eb2374e40214ce6575a29e755b707ca23

[[email protected] ~]# docker ps
CONTAINER ID        IMAGE                     COMMAND             CREATED             STATUS              PORTS               NAMES
7ce403eba8d8        docker.io/ubuntu:latest   "bash"              4 seconds ago       Up 3 seconds                            hungry_babbage
[[email protected] ~]# docker export -o test.tar 7ce403eba8d8

[[email protected] ~]# ls
anaconda-ks.cfg  test.tar

[[email protected] ~]# docker import test.tar test/ubuntu:v0.1
sha256:c3d604273769f7a74126b27f29c8cecd055fc18b10c943da0c0528dc28520a60

[[email protected] ~]# docker images
REPOSITORY          TAG                 IMAGE ID            CREATED             SIZE
test/ubuntu         v0.1                c3d604273769        4 seconds ago       72.8 MB
docker.io/ubuntu    latest              fb52e22af1b0        3 weeks ago         72.8 MB

[[email protected] ~]# docker run -itd test/ubuntu:v0.1
/usr/bin/docker-current: Error response from daemon: No command specified.
See '/usr/bin/docker-current run --help'.

# add /bin/bash work
[[email protected] ~]# docker run -itd test/ubuntu:v0.1 /bin/bash
5b7dca448a1400716fa931463c2c314e0e59c7888fa77d5b182e72d911122966

[[email protected] ~]# docker ps
CONTAINER ID        IMAGE                     COMMAND             CREATED             STATUS              PORTS               NAMES
5b7dca448a14        test/ubuntu:v0.1          "/bin/bash"         3 seconds ago       Up 2 seconds                            zen_varahamihira
7ce403eba8d8        docker.io/ubuntu:latest   "bash"              5 minutes ago       Up 5 minutes                            hungry_babbage

Read More:

RRS feed

  • Remove From My Forums
  • Question

  • Title says it all, CMD command from base image dockerfile is not being exposed to the container instance, how do I start up the container?

    the following does not work either

    docker run -d -p 8081:80 —name=test microsoft/sample-httpd:windowsservercore «c:Apache24binhttpd.exe -w»

    (yes theat command line path exists)

All replies

  • Try escaping the in the command with an additional . Check this out, has the same example which was working when the doc was written. So the command would look like this ‘c:\Apache24\bin\httpd.exe -w’.

    Dockerfiles on Windows

    neilp

  • C:Windowssystem32> docker run -d -p 8081:80 —name=test microsoft/sample-httpd:windowsservercore «c:\Apache24\bin\httpd.exe -w»
    996f5f967272082cfca3620442bc9f770b003e06a574353536ec430d65193033
    docker: Error response from daemon: Container command ‘c:\Apache24\bin\httpd.exe -w’ not found or does not exist.

So I am creating a docker image with packer.
The template defines the provisioners and builders etc.
The builder section looks like this:

{
    "builders": [
        {
            "type": "docker",
            "image": "ubuntu:latest",
            "export_path": "image.tar",
            "changes": [
                "USER test",
                "WORKDIR /tmp",
                "VOLUME /data",
                "EXPOSE 21 22",
                "CMD sudo myprogram"
            ]
        }
    ]
}

When running packer against the template, the output is an image.tar file.
I can then import it: docker import image.tar.
And then I start like this docker run -p 21:21 -it --rm 52c0b0362362 bash.

I want whenever the image is started that automatically sudo myprogram is executed. However it does not seem to work, even tho the template validated successfully. I also tried instead of specifying CMD sudo myprogram to set it as entrypoint like so: ENTRYPOINT sudo myprogram.
Neither worked. How can I make sure whenever my image is started, this command is automatically executed? It must be run as root/with sudo, that’s important.

030's user avatar

030

12.9k12 gold badges64 silver badges163 bronze badges

asked Dec 2, 2019 at 15:33

Kyu96's user avatar

5

And then I start like this docker run -p 21:21 -it --rm 52c0b0362362 bash

This would not work by design. When you run the image with the command above you are instructing Docker to overwrite the CMD instruction from your Dockerfile and therefore telling it to execute bash instead of sudo myprogram. It doesn’t matter what you have set in the CMD instruction — it would never be executed.

One way you could go around this would be to use ENTRYPOINT as others have suggested. This will make sudo myprogram the default command and then CMD can act as «additional arguments» to the default command (sudo myprogram).

Here’s a working example:

# build.json
{
    "builders": [
        {
            "type": "docker",
            "image": "ubuntu:latest",
            "commit": true,
            "changes": [
                "ONBUILD RUN apt-get -q update",
                "ONBUILD RUN apt-get install -y -q htop",
                "ENTRYPOINT ["top"]"
            ]
        }
    ]
}

# /packer build ./build.json

# run top with delay 3 sec
# docker run --rm -it sha256:hash

# run top with delay 1 sec
# docker run --rm -it sha256:hash -d 1

The other solution would be to keep the CMD ["sudo myprogram"] instruction but to run the image without adding a command at the end: docker run -it --rm HASH_ID.

answered Dec 8, 2019 at 20:57

tftd's user avatar

tftdtftd

3711 silver badge7 bronze badges

According to @earcam one can run a docker inspect <id> to check whether an image contains a CMD. If one builds a docker image using the provided packer snippet in the Q&A, imports it and subsequently runs a docker inspect 1127c20077ef | grep -i cmd, the CMD has not been set:

"Cmd": null,

According to @Greendrake when has to set the context when importing an image by defining --change 'CMD ["somecommand"]'

docker import --change 'CMD ["bash"]' image.tar

and subsequently issue an:

docker inspect b604fa244510 | grep -A3 -i cmd
        "Cmd": [
            "bash"
        ],

Once the image has been imported and docker run is issued a shell is opened:

docker run -it b604fa244510
root@69df4b3f48a2:/#

instead of

docker run -p 21:21 -it --rm 02163a32f3b7
docker: Error response from daemon: No command specified.
See 'docker run --help'.

answered Dec 7, 2019 at 20:51

030's user avatar

030030

12.9k12 gold badges64 silver badges163 bronze badges

Понравилась статья? Поделить с друзьями:
  • Docker error response from daemon driver failed programming external connectivity on endpoint
  • Docker error response from daemon could not select device driver with capabilities gpu
  • Docker error response from daemon conflict unable to remove repository reference
  • Docker error response from daemon conflict the container name is already in use by container
  • Docker error response from daemon cgroups cannot find cgroup mount destination unknown