Sunday, December 1, 2019

Docker


1. docker container can be find / downloaded from docker hub / docker store.

    http://hub.docker.com
 
    i.e
        $docker run ansible
        $docker run mogodb
        $docker run redis
        $docker run nodejs
     
2. Docker have two addition
    i. Community Edition
    ii. Enterprise Edition
 
3. Community Edition are availble for mac/windows/cloud (AWS)

4. Install docker desktop for windows / mac from http://docs.docker.com/install

5.  It will be eaiser to install docker through convenience script, instruction must  be found on http://docs.docker.com/install

6. Download images/container from http://hub.docker.com

7. To test visit the hub.docker and search for whalesay image to test the docker installation.

 $sudo docker run docker/whalesay cowsay HelloWorld

 Docker will pull the image and runs it.

 8. Docker Command
    i. $docker run <<container-name>> : to run the image, the image will be downloaded if not available.
 
    ii. $docker ps : will list all the containers
             -a : show the status and other details
           
    iii. $docker stop <<container-name>>
 
    iv. $docker rm <<container-name>> : remove the installed docker.
 
    v. $docker images : list down the downloaded images.
 
    vi. $docker rmi <<image-name>> : to remove the downloaded image.
        a. Stop and delete all the dependent container to remove image.
     
    vii. $docker pull <<image-name>> : just to pull the image without running it.
 
    viii. $docker run ubuntu : to run the container
 
    ix. $docker ps -a : list down the running container.
 
    x. Why the containers are in Exited status?
        Containers are ment to run process / tasks /webserer / application server/database instance not operating system once the task / process is completed the container exists.
     
        $docker run ubuntu sleep 5 : the ubuntun imaghe will start and sleep for 5 seconds one the task is completed the ubuntu iamge will be in Existed.
     
    xi. $docker exec distracted_mcclintock cat /etc/hosts : execute command inside the container to display the file content.
 
    xii. Processes runs either on four ground / active mode.
        a. $docker run kodekloud/simple-webapp : Run the image on attached mode.
     
        b. $docker run -d kodekloud/simple-webapp : Run the image in detach mode (backgroundm ode).
 
        - $kdocker attach <<image-name>> / <<image-id>> : to connect the detach container run the following command

        - first five character of docker image id are enough to run any docker command.
     
    ix. $docker run redis : to run the latest redis server
        $docker run redis:4.0 : to run the older version redis use the tag, the tag can be used with any image.
     
    xx. The hub.docker.com listdown all the versions / tags for all the available images.
 
    xxi. $docker run -i my/simple-prompt-docker : where -i is for an interactive mode to receive command line input and pass as parameter in application.
         $docker run -it my/simple-prompt-docker : for more interactive mode where you will see the application asking for input and you need to type you value and application will process that input further.
       
    xxii. Port forwarding:
 
    $docker run my/webapp: to start the web application image, the webapp is running on 5000 port (i.e http://172.17.0.2:5000/). Every machine have default IP and only accessable from docker host and not accessable outside the host.
 
    $docker run -p 80:5000 my/webapp : Map the port to access docker webapp image instance running on 5000 port.
 
    - this way you can run multipule instance of application using different ports.
    i.e
      $docker run -p 8000:5000 my/webapp
      $docker run -p 9000:5000 my/webapp
   
      $docker run -p 3306:3306 mysql
      $docker run -p 8306:3306 mysql
      $docker run -p 9306:3306 mysql
   
      - all above host ports are forwarded to one post of docker image.
 
    xxiii. Volume Mapping
 
    i.e $docker run mysql
        $docker stop mysql
        $docker rm mysql
     
        Onec the container removed all the data inside mysql database will be removed as well to prevent this we need to map the mysql data files with host file path.
     
        $docker run -v /opt/datadir:/var/lib/mysql mysql
     
        one the container starts with volume mapping all the data will be stored in the host system. Removing the mysql container will not effect the stored data.
     
    xxiv. Inspect Container:
        $docker inspect <<container-name>> : will return the json contain the details about container.
     
    xxv. Container logs (Processing running in detach mode)
     
        $ docker logs <<container-name>>
     
    xxvi. Set Environment Variables:
        The environment varabiles can be used inside the application and to set those run the following command:
     
        $docker run -e APP_COLOR=blue myweb
        $docker run -e APP_COLOR=red myweb
        $docker run -e APP_COLOR=green myweb
     
        to view the envrionment variable of container use inspect command
     
        $docker inspect <<container-name>>
        You will find the list of ENV in config tag of josn returned by inspect command.
 
     
9. Free lab to prectise the lab and quiz http://kodekloud.com/p/docker-labs

10. Create your own docker image.
    - Task list
        i. Install OS (ubuntu)
        ii. Update apt repository
        iii. Install apt updates
        iv. Install the python and its dependencies
        v. Copy the source
        vi. Run the application
     
       
    - Process
        i. Create docker file 'Dockerfile' and put all the commands are you will execute on OS.
     
            i.e
            --------------------------------
            FROM Ubuntu

            RUN apt-get update
            RUN apt-get install python
            RUN pip install flask
            RUN pip install flask-mysql

            COPY ./opt/source-code

            ENTRYPOINT FLASK_APP=/opt/source-code/app.py flask run
            ----------------------------------
         
            - In the above file, everything on left (i.e FORM, RUN, COPY) are instruction and text on the right side are Argument.
         
            -FROM Ubuntu: deifne the base OS required for docker image.

        ii. Build you image with docker build command using Dockerfile as parameter.
     
        $docker build Dockerfile -t isyed/my-python-app

        or
     
        $docker build .
            - If you want to re-run / contine if the building image failed on any step.
     
        iii. Run the push command to push the newly created image to public hub docker repository.
     
        $docker push isyed/my-python-app
            - here isyed is my account name which is created on docker website.
     
        $docker history isyed/my-python-app
            - to know the history and size of container image.
        

Design Patterns

Singleton 
---------------
class App{
    private App(){}
    static App createInstance(){}
}


Factory
---------------
interface App{
    public void develop();
    public void test();
    public void debug();
    public void deliver();
}
public class IOSApp implements App{}
public class TVApp implements App{}
public class WatchApp implements App{}

class AppStoreFactory{
   public App createApp(AppType type) {
       App app;
       switch (type) {
       case IOS:
           app = new IOSApp();
           break;
       case TV:
           app = new TVApp();
           break;
       case GLASS:
           app = new GlassApp();
           break;
       default:
           app = new GlassApp();
           break;
       }
       return app;
   }
}

Composite
---------------
Compose objects into tree structures to represent part-whole hierarchies. Composite lets client treat individual objects and compositions of objects uniformly.

Employee
Manager implements Employee
VP extends Manager
SectionManager extends Manager
TeamLeader extends Manager
Developer implements Employee

Adapter
---------------
Convert the interface of a class into another interface clients expect. Adapter lets classes work together that couldn’t otherwise because of incompatible interfaces.


Prototype
---------------
public abstract class App implements Cloneable {}
public class IOSApp extends App {}
public class WatchApp extends App {}


public class BasicAppCache {
     public void load() {}
     public App get(AppType type) {}
}

or

public class AdvancedAppCache {
    private App load(AppType type) {}
    public App get(AppType type) {}
}


public class AppFactory {
    BasicAppCache appCache;
    public App createApp(AppType type) {
        return this.appCache.get(type);
    }
}

public class AppStore {
    public static void main(String... args) {
        final App app = new AppFactory().createApp(AppType.WATCH));
    }
}


Proxy
--------------
Allows for object-level access control by acting as a pass-through entity or a placeholder object.

public interface Book {}
public class RealBook implements Book {}
public class ProxyBook implements Book {}
public class LibraryService {

}

Object-Oriented Design Principles (OODP)



1. DRY (Don't repeat yourself) : Don't duplicate code reusability is the best approach.

2. Encapsulate What Changes: Use the access specified wisely and not everything should be public (class/object/variable).

3. Open Closed Design Principle: Classes, methods or functions should be Open for extension (new functionality) and Closed for modification.

4. Single Responsibility Principle (SRP) : There should not be more than one reason for a class to change, or a class should always handle single functionality.

5. Dependency Injection or Inversion principle

6. Favor Composition over Inheritance : Always favor composition over inheritance. Composition allows changing the behavior of a class at run-time by setting property during run-time and by using Interfaces to compose a class we use polymorphism which provides flexibility to replace with better implementation at any time.

7. Liskov Substitution Principle (LSP) : Methods or functions which use the superclass type must be able to work with the object of subclass without any issue.

8. Interface Segregation Principle (ISP) : A client should not implement an interface if it doesn't use that. This happens mostly when one interface contains more than one functionality, and the client only needs one functionality and no other.

9. Programming for Interface not implementation 

10. Delegation principles : Don't do all stuff by yourself,  delegate it to the respective class. Classical example of delegation design principle is equals() and hashCode() method in Java.

Tuesday, July 16, 2019

Apache Reverse Proxy with mod_proxy

Follow the steps to install and configure apache as a reverse proxy. 

1. Install apache2 

    sudo apt-get update; sudo apt-get upgrade; sudo apt-get install apache2


2. Enable apache2 modules 

     sudo a2enmod proxy
     sudo a2enmod proxy_http
     sudo a2enmod proxy_balancer
     sudo a2enmod lbmethod_byrequests

3. Update apache2 default configuration file 

     sudo vi /etc/apache2/sites-available/000-default.conf

       <VirtualHost *:80>
              ProxyPreserveHost On
              ProxyPass / http://localhost:8080/
              ProxyPassReverse / http://localhost:8080/

              ErrorLog ${APACHE_LOG_DIR}/error.log
              CustomLog ${APACHE_LOG_DIR}/access.log combined
       </VirtualHost>

Multiple hosts:

<VirtualHost *:80>
    ProxyPreserveHost On
    ProxyPass /web http://localhost:8080/web
    ProxyPassReverse /web http://localhost:8080/web

    ProxyPass /micro http://localhost:8081/micro
    ProxyPassReverse /micro http://localhost:8081/micro
        
#ServerAdmin webmaster@localhost
#DocumentRoot /var/www/html

ErrorLog ${APACHE_LOG_DIR}/error.log
CustomLog ${APACHE_LOG_DIR}/access.log combined

</VirtualHost>

4. Restart the apache2 server 
        sudo systemctl restart apache2





Saturday, March 2, 2019

Enable CORS on Wildfly

Cross-Origin Resource Sharing (CORS) response headers to Camunda REST engine in wildfly (standalone.xml) distribution.

<subsystem xmlns="urn:jboss:domain:undertow:3.0">

    <buffer-cache name="default"/>
    <server name="default-server">
        <http-listener name="default" socket-binding="http" redirect-socket="https"/>
        <host name="default-host" alias="localhost">
            <location name="/" handler="welcome-content"/>
            <filter-ref name="server-header"/>
            <filter-ref name="x-powered-by-header"/>
            <filter-ref name="Access-Control-Allow-Origin"/>
            <filter-ref name="Access-Control-Allow-Methods"/>
            <filter-ref name="Access-Control-Allow-Headers"/>
            <filter-ref name="Access-Control-Allow-Credentials"/>
            <filter-ref name="Access-Control-Max-Age"/>
        </host>
    </server>
    <servlet-container name="default">
        <jsp-config/>
        <websockets/>
    </servlet-container>
    <handlers>
        <file name="welcome-content" path="${jboss.home.dir}/welcome-content"/>
    </handlers>
    <filters>
        <response-header name="server-header" header-name="Server" header-value="WildFly/10"/>
        <response-header name="x-powered-by-header" header-name="X-Powered-By" header-value="Undertow/1"/>
        <response-header name="Access-Control-Allow-Origin" header-name="Access-Control-Allow-Origin" header-value="*"/>
        <response-header name="Access-Control-Allow-Methods" header-name="Access-Control-Allow-Methods" header-value="GET, POST, OPTIONS, PUT"/>
        <response-header name="Access-Control-Allow-Headers" header-name="Access-Control-Allow-Headers" header-value="accept, authorization, content-type, x-requested-with"/>
        <response-header name="Access-Control-Allow-Credentials" header-name="Access-Control-Allow-Credentials" header-value="true"/>
        <response-header name="Access-Control-Max-Age" header-name="Access-Control-Max-Age" header-value="1"/>
    </filters>
</subsystem>


For Testing: http://www.apirequest.io/



AWS EC2 - SSH locked with UFW

Need to update the instance's user data: 1. Stop the instance 2. Right click (windows) or ctrl + click (Mac) on the instance to open a c...