问题
I intended to install a mongodb docker container from Docker Hub, and then insert some data into it. Obviously, a mongodb seed container is needed. So I did the following:
created a
Dockerfile
of Mongo seed container inmongo_seed/Dockerfile
and the code inDockerfile
is the following:FROM mongo:latest WORKDIR /tmp COPY data/shops.json . COPY import.sh . CMD ["/bin/bash", "-c", "source import.sh"]
The code of
import.sh
is the following:#!/bin/bash ls . mongoimport --host mongodb --db data --collection shops --file shops.json
the
shops.json
file contains the data to be imported to Mongocreated a
docker-compose.yml
file in the current working directory, and the code is the following:version: '3.4' services: mongodb: image: mongo:latest ports: - "27017:27017" container_name: mongodb mongodb_seed: build: mongodb_seed links: - mongodb
The code above successfully made the mongodb
service execute the import.sh
to import the json data - shops.json
. It works perfectly in my Ubuntu. However, when I tried to run command docker-compose up -d --build mongodb_seed
in Windows, the import of data failed with errors logs:
Attaching to linux_mongodb_seed_1
mongodb_seed_1 | ls: cannot access '.'$'\r': No such file or directory
: no such file or directory2T08:33:45.552+0000 Failed: open shops.json
mongodb_seed_1 | 2019-04-02T08:33:45.552+0000 imported 0 documents
Anyone has any ideas why it was like that? and how to fix it so that it can work in Windows as well?
回答1:
Notice the error ls: cannot access '.'$'\r': No such file or directory
.
One of the issues with Docker (or any Linux/macOS based system) on Windows is the difference in how line endings are handled.
Windows ends lines in a carriage return and a linefeed \r\n
while Linux and macOS only use a linefeed \n
. This becomes a problem when you try to create a file in Windows and run it on a Linux/macOS system, because those systems treat the \r
as a piece of text rather than a newline.
Make sure to run dos2unix
on script file whenever anyone edit anything on any kind of editor on Windows. Even if script file is being created on Git Bash don’t forget to run dos2unix
dos2unix import.sh
See https://willi.am/blog/2016/08/11/docker-for-windows-dealing-with-windows-line-endings/
In your case:
FROM mongo:latest
RUN apt-get update && apt-get install -y dos2unix
WORKDIR /tmp
COPY data/shops.json .
COPY import.sh .
RUN dos2unix /import.sh && apt-get --purge remove -y dos2unix
CMD ["/bin/bash", "-c", "source import.sh"]
回答2:
You can try to change line endings to UNIX in your script file.
来源:https://stackoverflow.com/questions/55470358/how-to-seed-a-docker-container-in-windows