Dockerfile
Create a Dockerfile
  • 1. Start from a Linux image
  • docker run -it ubuntu bash
    or
    docker run -it alpine sh
            
  • 2. Copy the code to the running Linux container
  • docker cp
            
  • 3. Install packages
  • pip install --no-cache-dir -r requirements.txt
            
  • 4. Run and test the app in the container, may need to map port in step 1
  • 5. Create a Dockerfile using the commonds conducted in step 1-4
  • Dockerfile Format
    # A Dockerfile must begin with a FROM instruction
    # Specifies the Parent Image
    FROM imageName
    
    # Execute any commands in a new layer on top of the current image and commit the result
    # Committed image will be used for the next step in the Dockerfile
    RUN [command]
    
    # Provide defaults for an executing container
    # Only one CMD instruction in a Dockerfile
    CMD [command]
    CMD echo "Hello World" # (shell form)
    CMD ["echo", "Hello World"] # (exec form)
    
    # Add metadata to an image
    LABEL [metadata]
    
    # Expose the container port number when running the container
    # It functions as a type of documentation between developers and users, exposed port number should match the port number of the app
    EXPOSE [portNumber]
    
    # Sets the environment variable
    ENV MY_NAME="Lin"
    
    # Copy new files, directories or remote file URLs from <src> and adds them to the filesystem of the image at the path <dest>
    # Copy and auto-extract tar files
    ADD [src] [dest]
    
    # Copy local files and directories from src to dest
    COPY [src][dest]
    
    # Configure a container that will run as an executable
    # Cannot add a command after the image
    # docker run [imageName], legal
    # docker run [imageName] sh, illegal, sh is taken as the parameter of ENTRYPOINT command
    ENTRYPOINT [command]
    
    # Set the user name for RUN, CMD and ENTRYPOINT instructions
    USER [userName]
    
    # Set the working directory for any RUN, CMD, ENTRYPOINT, COPY and ADD instructions
    WORKDIR [dirName]
    
    # Define the commands will be executed when the image is used as base
    # Not affect the current image build
    ONBUILD [DockerKey] [command]
    		
    .dockerignore
  • Avoid unnecessarily sending large or sensitive files and directories to the daemon with ADD and COPY
  • # comment
    */temp*
    */*/temp*
    temp?
    
    *.md
    !README.md # exception
            
    Build Image
    docker build -t [imageName] .
    
    # Check the size of each layer
    docker history [iamgeName]
            
    Create Container
    docker run [imageName]
    
    # -e, create environment variables
    docker run -e ENV_NAME=value [imageName]
            
    Reference
  • Dockerfile reference