Bacteria are capable of utilizing lactose due to the production of the enzyme, beta-galactosidase, that breaks it down into glucose and galactose units. Thus, the bacteria has lac operon (an operon is a set of genes involved in the same or different mechanism) in its chromosome.
The lac operon has 3 structural genes – lac Z (encodes the enzyme), lac Y (encodes lactose permease) and lac A (encodes o-acetyltransferase). It also has a promoter, an operator and lac I gene which encodes a repressor protein. The promoter overlaps with the operator region.
In absence of lactose, the repressor protein is produced (as lac I gene has its own promoter upstream of it) which binds to the operator region and prevents binding of RNA polymerase. As a result, no transcription of the structural genes takes place. But when there is abundant lactose available, it binds to the bound repressor, induces a conformational change and consequently the repressor falls off. Subsequently, RNA polymerase binds to the promoter region and begins transcribing the genes downstream of the lac promoter.
But how does the lactose molecule enter the bacterial cell when the operon is inactive? Some amount of basal transcription still happens. Thus, it is a leaky system. The lactose permease protein, thereby produced in the cell, allows the small amounts of beta-galactosidase to be exported into the environment where it converts lactose to allolactose. This allolactose then enters the cell and binds to the repressor protein preventing it to bind to the promoter-operator region. The operon gets activated and transcription at maximal rate ensues.
The IPTG has the same effect. The structure of IPTG is same as that of allolactose. It is small enough to enter the bacteria and produce the same effect. X-gal is incorporated into such plates to ensure that the colonies are synthesizing the functional enzyme by producing blue colonies in gene cloning experiments.