How to seed a docker container in Windows

2019-07-27 14:05发布

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:

  1. created a Dockerfile of Mongo seed container in mongo_seed/Dockerfile and the code in Dockerfile 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 Mongo

  2. created 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?

2条回答
趁早两清
2楼-- · 2019-07-27 14:23

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"]
查看更多
时光不老,我们不散
3楼-- · 2019-07-27 14:28

You can try to change line endings to UNIX in your script file.

查看更多
登录 后发表回答